2016-04-25 55 views
5

在app.js,我有如何在express.js中引发404错误?

// 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? 
    } 
+0

这是在一个页面请求或页面请求中的承诺内调用Posts.findOne'吗? –

回答

3

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是数据库代码没有找到任何东西的直接结果,所以在路由处理程序中有响应是有意义的。

0

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

app.use('/', my_router); 
.... 
app.use('/', my_router); 

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

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

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

next()功能将调用下一个中间件这是error404处理程序,如果它恰好位于app.js中的路由之后。