首页 > 解决方案 > 如何在 express 上为 404 错误添加中间件

问题描述

环境

app.use("/api/tobaccos", tobaccos);

app.use(function(err, req, res, next) {
  console.error(err.message);
});

接口:

router.get("/:id", async (req, res) => {
  console.log("GET TOBACCO:" + req.params.id);

  await Tobacco.findById(req.params.id)
    .then(tobacco => res.status(200).json({ status: "success", data: tobacco }))
    .catch(error => res.status(404).json({
      status: "fail",
      msg: "Tobacco not found!",
      code: "error.tobaccoNotFound"
    }));

});

我正在尝试为所有 404 错误添加中间件

app.use(function(err, req, res, next) {
  console.error(err.message);
});

或者这不起作用

app.get('*', function(req, res){
  res.status(404).send('what???');
});

怎么了?

标签: javascriptnode.jsexpressmiddleware

解决方案


在 Express 中,404 响应不是错误的结果,因此错误处理程序中间件不会捕获它们。这种行为是因为 404 响应只是表明没有额外的工作要做;也就是说,Express 已经执行了所有的中间件函数和路由,发现没有一个响应。您需要做的就是在堆栈的最底部(在所有其他函数下方)添加一个中间件函数来处理 404 响应:

app.use(function (req, res, next) {
  res.status(404).send("Sorry can't find that!")
})

在运行时在 express.Router() 的实例上动态添加路由,这样路由就不会被中间件函数取代。

参考:https ://expressjs.com/en/starter/faq.html


推荐阅读