Connect or Express middleware to modify the response.body

前端 未结 5 1523
一个人的身影
一个人的身影 2020-12-03 02:21

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

This is for an express server.

Something like:

function modify(         


        
相关标签:
5条回答
  • 2020-12-03 03:03

    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.

    0 讨论(0)
  • 2020-12-03 03:14

    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

    0 讨论(0)
  • 2020-12-03 03:16

    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');
    
    0 讨论(0)
  • 2020-12-03 03:22

    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.

    0 讨论(0)
  • 2020-12-03 03:26

    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.

    0 讨论(0)
提交回复
热议问题