首页 > 解决方案 > 不同路线的404页面不起作用

问题描述

我创建了一个站点,该站点具有根目录、帮助和 404 路径以及 hbs 格式的页面。问题是,当我运行localhost:3000/wrong它时,它会正确显示站点,但是当我运行localhost:3000/help/wrongcss 部分时,它并没有按应有的方式应用于该 404 页面,因为没有 route /help/wrong。 我使用or
运行代码。 文件夹结构:node app.jsnodemon app.js

  • 上市
    • css
      • 样式.css
  • 模板
    • 部分
      • 动物.hbs
      • 信息.hbs
    • 意见
      • 404.hbs
      • 帮助.hbs
      • 索引.hbs
  • 应用程序.js
  • 包.json
  • 包-lock.json

包.json

"dependencies": {
 "express": "^4.17.1",
 "hbs": "^4.1.1"
},
"devDependencies": {
 "nodemon": "^2.0.7"
}

应用程序.js

const express = require("express");
const hbs = require("hbs");

const app = express();

app.set('view engine', 'hbs');
app.set('views', './templates/views');
hbs.registerPartials('./templates/partials');
app.use(express.static('./public'));

const animal = 'Tiger';
app.get('', (request, response, next) => {
    response.render('index', {
        title: 'Root',
        animal
    });
})

app.get('/help', (req, res) => {
    res.render('help', {
        title: 'Help',
        animal
    })
})

app.get('/help/*', (req, res) => {
    res.render('404', {
        title: '404',
        animal,
        error: 'Help Page Not Found!'
    })
})

app.get('*', (req, res) => {
    res.render('404', {
        title: '404',
        animal,
        error: 'Page Not Found!'
    })
})

app.listen(3000, () => {
    console.log("Server is on port 3000");
})

索引.hbs

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Root</title>
    <link rel="stylesheet" href="css/styles.css">
</head>
<body>
    {{>info}}
    {{>animal}}  
</body>
</html>

帮助.hbs

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Help</title>
    <link rel="stylesheet" href="css/styles.css">
</head>
<body>
    {{>info}}
    {{>animal}}
</body>
</html>

404.hbs

<!DOCTYPE html>
<html lang="en">
<head>
    <title>404</title>
    <link rel="stylesheet" href="css/styles.css">
</head>
<body>
    {{>info}}
    {{error}}
    {{>animal}}
</body>
</html>

动物.hbs

<p>Animal is {{animal}}</p>

信息.hbs

<h1>{{title}}</h1>
<a href="/">Root</a>
<a href="/help">Help</a>

样式.css

body {
    background-color: teal;
}

我已经尝试尽可能地解释这个问题。如果有任何不清楚的地方,请发表评论。太感谢了。

标签: cssnode.jsexpresshandlebars.js

解决方案


app.get('/help*', (req, res) => {
    res.render('404', {
        title: '404',
        animal,
        error: 'Help Page Not Found!'
    })
})

删除/之前*的伎俩吗?


推荐阅读