javascript - 为什么以下处理程序被识别为404处理程序

标签 javascript node.js express middleware

我正在查看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/

相关文章:

javascript - Nodejs异步 waterfall 在第二个函数中使用mongoose findOneAndUpdate

javascript - Handsontable:将列作为参数数组从服务器传递

javascript - Uncaught ReferenceError : require is not defined - Node. js

node.js - 尝试 - 当 JSON 有反斜杠时,Catch 没有正确响应

mysql - 使用 Express 中 Sequelize 中的创建方法检查表中存在的 ID

javascript - 通过key进行区分,然后得到key以外字段的结果

javascript - 在 JQUERY 中创建 HTML 后,Jquery 方法不起作用

javascript - 尝试获取 process.env node.js 时出现 SyntaxError : Unexpected token .

node.js - 无法使用express js在mongodb中一次$push和$set数据

node.js - 扩展 Express 应用程序接口(interface)