Reputation: 867
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.
Upvotes: 5
Views: 7498
Reputation: 635
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");
});
}
}));
Upvotes: 3
Reputation: 1
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
Upvotes: 0