【问题标题】:Connect or Express middleware to modify the response.body连接或Express中间件修改response.body
【发布时间】:2012-04-11 09:40:11
【问题描述】:

我想要一个修改响应正文的中间件函数。

这是一个快速服务器。

类似:

function modify(req, res, next){
  res.on('send', function(){
    res.body = res.body + "modified"
  });

  next();
}

express.use(modify);

我不明白要听什么事件。任何帮助或文档将不胜感激。

【问题讨论】:

    标签: node.js express connect


    【解决方案1】:

    express-mung 就是为此而设计的。而不是事件,它只是更多的中间件。你的例子看起来像

    const mung = require('express-mung')
    
    module.exports = mung.json(body => body.modifiedBy = 'me');
    

    【讨论】:

    • 易于使用的库!
    【解决方案2】:

    用 Express 4 覆盖响应的 write 方法似乎对我有用。这允许修改响应的主体,即使它是流。

    app.use(function (req, res, next) {
      var write = res.write;
      res.write = function (chunk) {
        if (~res.getHeader('Content-Type').indexOf('text/html')) {
          chunk instanceof Buffer && (chunk = chunk.toString());
          chunk = chunk.replace(/(<\/body>)/, "<script>alert('hi')</script>\n\n$1");
          res.setHeader('Content-Length', chunk.length);
        }
        write.apply(this, arguments);
      };
      next();
    });
    

    只需确保在任何其他可能修改响应的中间件之前注册此中间件即可。

    【讨论】:

    • 为了简化你的答案而不是~res.getHeader('Content-Type').indexOf('text/html'),你可以使用res.getHeader('Content-Type').indexOf('text/html') &gt; -1
    【解决方案3】:

    似乎有一个名为 connect-static-transform 的模块可以执行此操作,请查看:

    https://github.com/KenPowers/connect-static-transform

    一个连接中间件,允许在提供静态文件之前对其进行转换。

    它带有示例,例如this one

    【讨论】:

    • 很遗憾,这个中间件的transform 回调没有收到来自中间件链的reqres 参数。
    【解决方案4】:

    我相信一旦中间件处理了请求,OP 实际上想要修改响应流。查看捆绑的 Compress 中间件实现,了解如何完成此操作的示例。 Connect Monkey 修补 ServerResponse 原型,以在调用 writeHead 时但在它完成之前发出 header 事件。

    【讨论】:

      【解决方案5】:

      您不需要监听任何事件。做就行了

      function modify(req, res, next){
        res.body = res.body + "modified";
      
        next();
      }
      

      然后use 在你use 路由器之后。这样,在您执行完所有路线后,您可以修改正文

      【讨论】:

      • 我正在尝试在路由器之后使用我的中间件,但它似乎根本没有触发。仅当我在 app.router 之前使用它时才会触发它。我在 app.configure 块中使用它,如果这有什么不同的话。
      • 确保你在路由中调用next,否则 express 不会在该路由之后执行任何中间件
      • 究竟是什么意思“在你use路由器之后”?在带有app.get(someRoute, handler)s 和app.listen(port, anotherHandler 的简单应用程序中,我必须在app.use(modify) 之后app.listen 吗?对我来说之前和之后似乎都不起作用(我添加了app.use((req, res, next) =&gt; { console.log('after response'); next(); })并且在控制台中看不到任何内容..
      • 不适用于express 4,根据Response 对象api doc 没有这样的属性或方法称为bodyapi doc
      猜你喜欢
      • 1970-01-01
      • 2015-06-16
      • 1970-01-01
      • 1970-01-01
      • 2020-09-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-14
      • 1970-01-01
      相关资源
      最近更新 更多