gpt4 book ai didi

node.js - 使用 Express 4 处理 404 错误

转载 作者:搜寻专家 更新时间:2023-10-31 22:22:29 24 4
gpt4 key购买 nike

我正在使用 Express 4,我有大约 50 个 html 页面。我正在尝试处理 404 错误,但不知道如何处理。我不想手动定义 Node 中的所有路由器。如果页面不存在,是否可以动态重定向到 404 Jade 模板?

我试过这段代码但没有成功:

app.enable('verbose errors');
app.set('port', 3000);

app.use(express.static(__dirname + '/html/'));

var server = http.createServer(app);
server.listen(app.get('port'), function() {
console.log('ONLINE !');
});

app.use(function(req, res, next) {
console.log('GET ' + req.originalUrl)
console.log('At %d', Date.now());
next();
});

// Handle 404
app.use(function(req, res, next) {
if(req.accepts('html') && res.status(404)) {
res.render('404.jade');
return;
}
});

最佳答案

这对我有用:

var express = require('express');
var app = express();

app.use(express.static('public'));

app.get('/', function (req, res) {
res.send('Hello World!');
});

app.get('/employee', function (req, res) {
res.send('Employee route !!');
});


// Handle 404 - Keep this as a last route
app.use(function(req, res, next) {
res.status(404);
res.send('404: File Not Found');
});

app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});

文件夹结构,

enter image description here

现在当我们发出这样的请求时

http://localhost:3000/sample

这已由中间件处理。

更新

不写get请求来显示html文件的方式就是这样的另一个中间件

app.use(express.static('public'));
app.use(express.static('views'));

恰好在“public”之后添加“views”中间件。

现在如果我们给

http://localhost:3000/index.html

页面已呈现。

关于node.js - 使用 Express 4 处理 404 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40204243/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com