【问题标题】:Overriding Expressjs response in middleware is not working在中间件中覆盖 Expressjs 响应不起作用
【发布时间】:2017-05-03 09:02:40
【问题描述】:

我想在返回之前修改响应正文,我使用了this answer的解决方案

但它不起作用,这是我的代码:

app.js

function modify(req, res, next) {
  var json = res.json;
  console.log("step 1");
  res.json = function(data) {
    console.log("step 2");
    json.call(this, "modified");
  };
  next();
}
app.use(modify);

在路由器中:

router.get('/',(req,res,next)=>{
  res.json('Welcome')
  next()
})

已调用中间件,但从未调用过覆盖函数(第 2 步),请告诉我我的代码有什么问题,谢谢!

【问题讨论】:

  • wrap 函数有什么作用?
  • @Shaharyar 只是一个向响应正文添加一些信息的函数
  • 在您的问题中也添加该功能

标签: node.js express


【解决方案1】:

使用 next() 仅用于传递给下一个函数

router.get('/',(req,res,next)=>{
    if(wantToStop=='true'){
       res.json('Welcome')
    }else{
      next()
   }

 })

【讨论】:

    猜你喜欢
    • 2012-09-12
    • 2019-09-12
    • 2016-01-17
    • 2019-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-03
    • 2018-02-28
    相关资源
    最近更新 更多