Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

socket hang up error with nodejs

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.

like image 850
codeofnode Avatar asked Aug 08 '14 15:08

codeofnode


2 Answers

Just for sake of completeness, there is really an integration problem between modules body-parser and http-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.

// 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've lost 2 days on this f***** problem. Hope it helps!

like image 109
riccardo.cardin Avatar answered Sep 29 '22 12:09

riccardo.cardin


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.

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');

});
like image 23
Vladik Y Avatar answered Sep 29 '22 11:09

Vladik Y