简体   繁体   English

如何在 express 上为 404 错误添加中间件

[英]How add middleware for 404 errors on express

setting环境

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

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

api: api:

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"
    }));

});

I'm trying to add middleware for all 404 errors我正在尝试为所有 404 错误添加中间件

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

or this doesn't work或者这不起作用

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

What is wrong?怎么了?

You can add this middleware in your root file.您可以在root文件中添加此middleware It sends error for any invalid routes.它为任何无效路由发送错误。

 //Handles 404 errors
app.use((req, res, next) => {
    const error = new Error('Error Occured');
    error.status = 404;
    next(error);
});
app.use((error, req, res, next) => {
    res.status(error.status || 500);
    res.json({
        error: {
            message: error.message
        }
    });
});

Alternatively, you can try which captures all 404 errors或者,您可以尝试捕获所有 404 错误

app.use(function(req, res, next) {
    res.status(404).send( 'Error Occured! ');
});

In Express, 404 responses are not the result of an error, so the error-handler middleware will not capture them.在 Express 中,404 响应不是错误的结果,因此错误处理程序中间件不会捕获它们。 This behavior is because a 404 response simply indicates the absence of additional work to do;这种行为是因为 404 响应只是表明没有额外的工作要做; in other words, Express has executed all middleware functions and routes, and found that none of them responded.也就是说,Express 已经执行了所有的中间件函数和路由,发现没有一个响应。 All you need to do is add a middleware function at the very bottom of the stack (below all other functions) to handle a 404 response:您需要做的就是在堆栈的最底部(在所有其他函数下方)添加一个中间件 function 来处理 404 响应:

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

Add routes dynamically at runtime on an instance of express.Router() so the routes are not superseded by a middleware function.在运行时在 express.Router() 的实例上动态添加路由,这样路由不会被中间件 function 取代。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM