在 app.js 中,我有
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
所以如果我请求一些不存在的 url,比如 http://localhost/notfound
,上面的代码将会执行。
在像 http://localhost/posts/:postId
这样的 url 中,我想在访问一些不存在的 postId 或删除的 postId 时抛出 404 错误。
Posts.findOne({_id: req.params.id, deleted: false}).exec()
.then(function(post) {
if(!post) {
// How to throw a 404 error, so code can jump to above 404 catch?
}
最佳答案
In Express, a 404 isn't classed as an 'error', so to speak - 这背后的原因是 404 通常不是出现问题的标志,它只是服务器找不到任何东西。最好的办法是在路由处理程序中明确发送 404:
Posts.findOne({_id: req.params.id, deleted: false}).exec()
.then(function(post) {
if(!post) {
res.status(404).send("Not found.");
}
或者,如果感觉重复代码太多,您可以随时将该代码提取到一个函数中:
function notFound(res) {
res.status(404).send("Not found.");
}
Posts.findOne({_id: req.params.id, deleted: false}).exec()
.then(function(post) {
if(!post) {
notFound(res);
}
我不建议在这种情况下使用中间件,仅仅是因为我觉得它会使代码不那么清晰——404 是数据库代码没有找到任何东西的直接结果,所以在路由处理程序。
关于javascript - 如何在 express.js 中抛出 404 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36837531/