Skip to content
Advertisement

Custom response with http-proxy-middleware package

In our project we’re using the “http-proxy-middleware”(https://www.npmjs.com/package/http-proxy-middleware) npm package for proxy.

There is the “onProxyRes” function to subscribe to http-proxy’s event.

And there is an example of that function:

function onProxyRes(proxyRes, req, res) {
  proxyRes.headers['x-added'] = 'foobar' // add new header to response
  delete proxyRes.headers['x-removed'] // remove header from response
}

I’m just interesting is it possible somehow based on proxyRes write changed response in res object and do not copy data directly from proxyRes object?

Just example:

proxyRes(readable stream contains the following data: {“url”: “http://domain/test“}, I’d like to modify that response and have res with data like that: {{“url”: “http://changedDomain/test“}} and do not copy data from proxyRes directly

Advertisement

Answer

Maybe it looks ugly little bit, but I’m able to manage that with the following code:

function onProxyRes(proxyResponse, request, serverResponse) {
  var body = "";
  var _write = serverResponse.write;
  proxyResponse.on('data', function (chunk) {
    body += chunk;
  });

  serverResponse.write = function (data) {
    try{
      var jsonData = JSON.parse(data);
      // here we can modify jsonData
      var buf = Buffer.from(JSON.stringify(jsonData), 'utf-8');
      _write.call(serverResponse,buf);
    } catch (err) {
      console.log(err);
    }
  }

}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement