我正在查看express生成器生成的app.js
,有以下代码:
app.use('/', index);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
我的问题是为什么最后一个中间件函数被标识为应该返回 not find
错误时执行的函数?
是否基于这样的假设:如果调用此函数,则意味着没有其他中间件/路由器函数使用 res.send()
完成了请求的处理,因此对该请求不感兴趣,所以可能没有该请求的处理程序?如果是这样,那么这个 404
处理函数应该始终添加到最后,对吗?
最佳答案
正如你所说,如 http://expressjs.com/en/starter/faq.html 中所述
How do I handle 404 responses? In Express, 404 responses are not the result of an error, so the error-handler middleware will not capture them. This behavior is because a 404 response simply indicates the absence of additional work to do; in other words, Express has executed all middleware functions and routes, and found that none of them responded. All you need to do is add a middleware function at the very bottom of the stack (below all other functions) to handle a 404 response:
app.use(function (req, res, next) { res.status(404).send("Sorry can't find that!") })
关于javascript - 为什么以下处理程序被识别为404处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41384975/