node.js 如何仅在缺少的路线上将 Express.js 设置为 404?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11500204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get Express.js to 404 only on missing routes?
提问by Hoa
At the moment I have the following which sits below all my other routes:
目前,我有以下所有其他路线:
app.get('*', function(req, res){
console.log('404ing');
res.render('404');
});
And according to the logs, it is being fired even when the route is being matched above. How can I get it to only fire when nothing is matched?
根据日志,即使路由在上面匹配,它也会被触发。我怎样才能让它只在没有匹配的情况下触发?
回答by Charles
You just need to put it at the end of all route.
你只需要把它放在所有路线的末尾。
Take a look at the second example of Passing Route Control:
看一下Passing Route Control的第二个例子:
var express = require('express')
, app = express.createServer();
var users = [{ name: 'tj' }];
app.all('/user/:id/:op?', function(req, res, next){
req.user = users[req.params.id];
if (req.user) {
next();
} else {
next(new Error('cannot find user ' + req.params.id));
}
});
app.get('/user/:id', function(req, res){
res.send('viewing ' + req.user.name);
});
app.get('/user/:id/edit', function(req, res){
res.send('editing ' + req.user.name);
});
app.put('/user/:id', function(req, res){
res.send('updating ' + req.user.name);
});
app.get('*', function(req, res){
res.send('what???', 404);
});
app.listen(3000);
Alternatively you can do nothing because all route which does not match will produce a 404. Then you can use this code to display the right template:
或者,您什么也不做,因为所有不匹配的路由都会产生 404。然后您可以使用此代码来显示正确的模板:
app.error(function(err, req, res, next){
if (err instanceof NotFound) {
res.render('404.jade');
} else {
next(err);
}
});
It's documented in Error Handling.
它记录在错误处理中。
回答by Justin Cloud
I bet your browser is following up with a request for the favicon. That is why you are seeing the 404 in your logs after the 200 success for the requested page.
我敢打赌,您的浏览器正在跟进对网站图标的请求。这就是为什么您在请求页面成功 200 后在日志中看到 404 的原因。
Setup a favicon route.
设置网站图标路由。
回答by Thai Ha
Hope it helpful, I used this code in bottom of routes
希望有帮助,我在路线底部使用了此代码
router.use((req, res, next) => {
next({
status: 404,
message: 'Not Found',
});
});
router.use((err, req, res, next) => {
if (err.status === 404) {
return res.status(400).render('404');
}
if (err.status === 500) {
return res.status(500).render('500');
}
next();
});
回答by kiko carisse
I wanted a catch all that would render my 404 page only on missing routes and found it here in the error handling docs https://expressjs.com/en/guide/error-handling.html
我想要一个捕获所有只会在丢失的路由上呈现我的 404 页面的内容,并在错误处理文档https://expressjs.com/en/guide/error-handling.html 中找到它
app.use(function (err, req, res, next) {
console.error(err.stack)
res.status(404).render('404.ejs')
})
This worked for me.
这对我有用。

