【问题标题】:How add middleware for all responses? (express.js)如何为所有响应添加中间件? (express.js)
【发布时间】:2020-07-07 09:34:34
【问题描述】:

我的目标是检查所有 200 个状态响应并检查数据,如果数据为空,我必须将此请求更改为 404 错误。可以快递吗?

设置

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

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

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

});

我正在尝试为此添加中间件,但它不起作用

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

或者这不起作用

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

怎么了?有可能吗?

【问题讨论】:

标签: node.js express middleware


【解决方案1】:

你可以用这个

app.use((err, req, res, next) => {
    console.log('err: ', err);
    res.status(err.hasOwnProperty('status') ? err.status : 500);
    res.json({
        message: err.hasOwnProperty('errors') ? err.errors : err.toString()
    });
});   

catch 块抛出的任何错误都会处理

【讨论】:

  • 我没有错误。中间件是关于向系统的任何部分添加代码
  • 我正在回答这个问题 app.use(function(err, req, res, next) { console.error(err.message); });
猜你喜欢
  • 2015-10-18
  • 1970-01-01
  • 1970-01-01
  • 2017-09-14
  • 1970-01-01
  • 2015-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多