Connect or Express middleware to modify the response.body

丶灬走出姿态 提交于 2019-12-17 11:42:10

问题


I would like to have a middleware function which modifies the response body.

This is for an express server.

Something like:

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

  next();
}

express.use(modify);

I don't understand what event to listen for. Any help or documentation would be appreciate.


回答1:


You don't need to listen to any events. Just make it

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

  next();
}

And use it after you use the router. This way after all your routes have executed you can modify the body




回答2:


I believe the OP actually wants to modify the response stream once a middleware has handled the request. Look at the bundled Compress middleware implementation for an example of how this is done. Connect monkey patches the ServerResponse prototype to emit the header event when writeHead is called, but before it is completed.




回答3:


express-mung is designed for this. Instead of events its just more middleware. Your example would look something like

const mung = require('express-mung')

module.exports = mung.json(body => body.modifiedBy = 'me');



回答4:


Overwriting the response's write method seemed to work for me with Express 4. This allows modifying the response's body even when it's a stream.

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

Just make sure to register this middleware before any other middleware that may be modifying the response.




回答5:


There seems to be a module for doing just this called connect-static-transform, check it out:

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

A connect middleware which allows transformation of static files before serving them.

And it comes with examples, like this one.



来源:https://stackoverflow.com/questions/9896628/connect-or-express-middleware-to-modify-the-response-body

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!