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:
var httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer({ target: argv.proxy_url })
proxy.on('error', function(err, req, res) {
res.end();
})
I had a similar issue and resolved it by moving my proxy code above other node middleware.
e.g. This:
var httpProxy = require('http-proxy');
var apiProxy = httpProxy.createProxyServer();
app.use("/someroute", function(req, res) {
apiProxy.web(req, res, { target: 'http://someurl.com'})
});
app.use(someMiddleware);
not this:
app.use(someMiddleware);
var httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer();
app.use("/someroute", function(req, res) {
proxy.web(req, res, { target: 'http://someurl.com'})
});
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 with body-parser middleware.
You may want to move the http-proxy middleware before body-parser or stop using body-parser.
See also: Socket hangup while posting request to Node-http-proxy Node.js