在 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);
});
所以如果我请求一些不存在的网址,例如http://localhost/notfound
,上面的代码将会执行。
在存在的网址中http://localhost/posts/:postId
,我想在访问一些不存在的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?
}
可以这么说,在 Express 中,404 不被归类为“错误”- 其背后的原因是,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 是数据库代码找不到任何内容的直接结果,因此在路由处理程序中包含响应是有意义的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)