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:
JavaScript
x
5
1
function onProxyRes(proxyRes, req, res) {
2
proxyRes.headers['x-added'] = 'foobar' // add new header to response
3
delete proxyRes.headers['x-removed'] // remove header from response
4
}
5
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:
JavaScript
1
20
20
1
function onProxyRes(proxyResponse, request, serverResponse) {
2
var body = "";
3
var _write = serverResponse.write;
4
proxyResponse.on('data', function (chunk) {
5
body += chunk;
6
});
7
8
serverResponse.write = function (data) {
9
try{
10
var jsonData = JSON.parse(data);
11
// here we can modify jsonData
12
var buf = Buffer.from(JSON.stringify(jsonData), 'utf-8');
13
_write.call(serverResponse,buf);
14
} catch (err) {
15
console.log(err);
16
}
17
}
18
19
}
20