如何在express.js中引发404错误?

在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 ,上面的代码将会执行。

在存在的URL像http://localhost/posts/:postId ,我想抛出404错误时访问一些不存在postId或删除postId。

 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通常不是一个错误的标志,而是服务器找不到任何东西。 你最好的select是在你的路由处理器中明确地发送一个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是数据库代码没有find任何东西的直接结果,所以在路由处理程序中有响应是有意义的。

我有相同的app.js结构,我用这种方式在路由处理程序中解决了这个问题:

 router.get('/something/:postId', function(req, res, next){ // ... if (!post){ next(); return; } res.send('Post exists!'); // display post somehow }); 

如果next()函数恰好在app.js中的路由之后,那么next()函数将调用下一个中间件,它是error404处理程序。

你可以使用这个和你的路由器的结束。

 app.use('/', my_router); .... app.use('/', my_router); app.use(function(req, res, next) { res.status(404).render('error/404.html'); });