I want to set up proxy for some XYZ server whose i am not the admin. Then i want to do some analysis over the request and response headers then also over request and response bodies. So i am using http-proxy https://github.com/nodejitsu/node-http-proxy
this is what i am doing :
var proxy = httpProxy.createProxyServer();
connect.createServer(
connect.bodyParser(),
require('connect-restreamer')(),
function (req, res) {
proxy.web(req, res, { target : 'XYZserver' });
}
).listen(config.listenPort);
Upto GET request everything is fine but whenever a request with some body like POST, PATCH, PUT etc request are made i get the error :
Error: socket hang up
at createHangUpError (http.js:1472:15)
at Socket.socketCloseListener (http.js:1522:23)
at Socket.EventEmitter.emit (events.js:95:17)
at TCP.close (net.js:466:12)
I google a lot but found no clue whats wrong going on. I enable socket proxy with 'ws:true' option of 'proxy.web' but still the same error.
Need catching proxy's errors:
After wasting more than a day and following some posts in nodejitsu/node-http-proxy issues I was able to make it working thanks to riccardo.cardin. I've decided to post full example to save you time. The below example uses server express, body-parser (req.body middleware) and ofcourse http-proxy to proxy and forward request to 3rd party server.
Just for sake of completeness, there is really an integration problem between modules
body-parser
andhttp-proxy
, as stated in this thread.If you can't change the order of the middleware; You can restream the parsed body before proxying the request.
I've lost 2 days on this f***** problem. Hope it helps!
I had a similar issue and resolved it by moving my proxy code above other node middleware.
e.g. This:
not this:
My specific issue was having BodyParser middleware above the proxy. I haven't done much digging but it must have modified the request in some way that broke the proxy library when the request finally came to it.
It seems that
http-proxy
is not compatible withbody-parser
middleware. You may want to move thehttp-proxy
middleware beforebody-parser
or stop usingbody-parser
.See also: Socket hangup while posting request to Node-http-proxy Node.js