4

I'm using Express 4, and I'm using a middleware http-proxy-middleware ( https://github.com/chimurai/http-proxy-middleware), and having the following issues

In normal way, I can do the following to manupulate the response before return to the client

app.get('/v1/users/:username', function(request, response, next) {
    var username = request.params.username;
    findUserByUsername(username, function(error, user) {
        if (error) return next(error);
        return response.render('user', user);
    });
});

But how do I execute custom logic if I'm using proxy, let's say I want to manipulate some of the data before response to the client? Is there a good pattern to do that with this middleware ?

app.use('/api', proxy({target: 'http://www.example.org', changeOrigin: true}));

Here is the backlink for the issue I put in github as well - https://github.com/chimurai/http-proxy-middleware/issues/97

Any help would be appreciated.

iMoses
  • 4,338
  • 1
  • 24
  • 39
R.R
  • 847
  • 1
  • 9
  • 20
  • Actually using this help https://github.com/langjt/node-http-proxy-json But currently it only support "gzip" and "deflate" as its content type. – R.R Aug 09 '16 at 00:59

2 Answers2

3

I think this is the correct way to do it according to the official documentation of http-proxy. modify -response

app.use('/api', proxy({
    target: 'http://www.example.org',
    changeOrigin: true,
    selfHandleResponse: true, // so that the onProxyRes takes care of sending the response
    onProxyRes: function(proxyRes, req, res) {
        var body = new Buffer('');
        proxyRes.on('data', function(data) {
            body = Buffer.concat([body, data]);
        });
        proxyRes.on('end', function() {
            body = body.toString();
            console.log("res from proxied server:", body);
            res.end("my response to cli");
        });
    }
}));
Sachin Mour
  • 635
  • 7
  • 16
0

here is my answer,

onProxyRes :function(proxyRes, req, res){
      var _write = res.write;
      var output;
      var body = "";
      proxyRes.on('data', function(data) {
          data = data.toString('utf-8');
          body += data;
      });
      res.write = function (data) {
        try{
/*** something detect if data is all download.my data is json,so I can do by this***/
          eval("output="+body)
          output = mock.mock(output)
          _write.call(res,JSON.stringify(output));
        } catch (err) {}
      }
    }

add onProxyRes option on the http-proxy-middleware use the data event on the proxyRes to get the output then modify the output in res.write