javascript - 如何在 express.js 中抛出 404 错误?

标签 javascript node.js express

在 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/

相关文章:

javascript - Element.bind 仅每隔一次 ng-click::(AngularJS + Ionic) 注册一次

javascript - 如何使用 webdriverio 单击并按住

javascript - 在网站中自定义 Braintree Drop-in UI

html - Node/快速 anchor 链接路由

javascript - JS 将单个索引中的 2 个数组及其各个值合并到 1 个数组中的单个索引中

javascript - 使用 gulp-watch 忽略隐藏文件

node.js - 在node.js中执行exe文件时传递多个参数

html - Express 中的 400/500 错误处理程序 - 发送 JSON 与 HTML

javascript - 如何在 firebase 上托管 Nodejs/Express 后端?

node.js - 使用node的ejs模板框架处理php文件