Socket hang error with nodejs

I want to configure a proxy for some kind of XYZ server, whose I am not an admin. Then I want to do some analysis on the request and response headers, as well as on the request and response authorities. So I use 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); 

The Upto GET request is OK, but whenever a request with some body, like a POST, PATCH, PUT, etc. request, I get an 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 googled a lot, but did not understand what was going on. I allow the socket proxy with the parameter "ws: true" in "proxy.web", but still the same error.

+6
source share
5 answers

I had a similar problem and resolved it by moving my proxy code over other middleware node.

eg. It:

 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 problem was having BodyParser middleware over the proxy. I didn’t do much, but I had to somehow modify the request that broke the proxy library when the request finally arrived at it.

+13
source

For completeness, there really is a problem of integration between the body-parser and http-proxy modules, as indicated in this thread.

If you can not change the order of the middleware; You can restream analyze the body before proxying the request.

 // restream parsed body before proxying proxy.on('proxyReq', function(proxyReq, req, res, options) { if (req.body) { let bodyData = JSON.stringify(req.body); // incase if content-type is application/x-www-form-urlencoded -> we need to change to application/json proxyReq.setHeader('Content-Type','application/json'); proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData)); // stream the content proxyReq.write(bodyData); } } 

I lost 2 days on this problem f *****. Hope this helps!

+7
source

Need to detect proxy errors:

 var httpProxy = require('http-proxy'); var proxy = httpProxy.createProxyServer({ target: argv.proxy_url }) proxy.on('error', function(err, req, res) { res.end(); }) 
+5
source

It seems that http-proxy not compatible with body-parser middleware. You might want to move the http-proxy middleware to body-parser or stop using body-parser .

See also: Breakdown of a socket when sending a request to Node -http-proxy Node.js

+2
source

After you lost more than a day and after some posts in nodejitsu / node-http-proxy issues , I was able to get it working thanks to riccardo.cardin. I decided to publish a complete example to save you time. The example below uses the express server, body-parser (middleware req.body) and, of course, http-proxy for the proxy server and redirect the request to a third-party server.

 const webapitargetUrl = 'https://posttestserver.com/post.php'; var bodyParser = require('body-parser'); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); // support json encoded bodies var https = require('https'); var stamproxy = httpProxy.createProxyServer({ target: 'https://localhost:8888', changeOrigin: true, agent : https.globalAgent, toProxy : true, secure: false, headers: { 'Content-Type': 'application/json' } }); stamproxy.on('proxyReq', function(proxyReq, req, res, options) { console.log("proxying for",req.url); if (req.body) { console.log("prxyReq req.body: ",req.body); // modify the request. Here i just by removed ip field from the request you can alter body as you want delete req.body.ip; let bodyData = JSON.stringify(req.body); // in case if content-type is application/x-www-form-urlencoded -> we need to change to application/json proxyReq.setHeader('Content-Type','application/json'); proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData)); // stream the content console.log("prxyReq bodyData: ",bodyData); proxyReq.write(bodyData); } console.log('proxy request forwarded succesfully'); }); stamproxy.on('proxyRes', function(proxyRes, req, res){ proxyRes.on('data' , function(dataBuffer){ var data = dataBuffer.toString('utf8'); console.log("This is the data from target server : "+ data); }); }); app.use(compression()); app.use(favicon(path.join(__dirname, '..', 'static', 'favicon.ico'))); app.use(Express.static(path.join(__dirname, '..', 'static'))); var sessions = require("client-sessions"); app.use(sessions({ secret: 'blargadeeblargblarg', cookieName: 'mysession' })); app.use('/server/setserverip', (req, res) => { console.log('------------ Server.js /server/setserverip ---------------------------------'); req.mysession.serverip += 1; console.log('session data:'); console.log(req.mysession.serverip) console.log('req.body:'); console.log(req.body); // Proxy forwarding stamproxy.web(req, res, {target: webapitargetUrl}); console.log('After calling proxy serverip'); }); 
+1
source

Source: https://habr.com/ru/post/973550/


All Articles