简体   繁体   中英

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

I don't think it's necessary to copy data to res as proxyRes already has changedDomain . Here is the set up I implemented:

const express = require('express');
const httpProxy = require('http-proxy-middleware');

const app = express();

app.use('/api', httpProxy({ target : 'sometarget.com', changeOrigin : true, onProxyRes})

function onProxyRes (proxyResponse, request, response) {
  console.log('proxyResponse', proxyResponse.headers);  
  console.log('response', response.headers);
}

// Results
/*
proxyResponse { date: 'Wed, 02 Jan 2019 12:06:40 GMT',
  server: 'Apache',
  location: 'http://sometarget.com/api',
  'cache-control': 'max-age=30',
  expires: 'Wed, 02 Jan 2019 12:07:10 GMT',
  'content-length': '231',
  connection: 'close',
  'content-type': 'text/html; charset=iso-8859-1' }
response undefined
*/

Everything you'll need will be in proxyRes unless you have a specific use for response ...

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM