gpt4 book ai didi

javascript - 为什么下面的handler被识别为404 handler

转载 作者:行者123 更新时间:2023-11-29 21:11:58 24 4
gpt4 key购买 nike

我正在查看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 found 错误时执行的函数?

是否基于以下假设:如果调用此函数,则意味着没有其他中间件/路由器函数使用 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 - 为什么下面的handler被识别为404 handler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41384975/

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