node.jsproxynode-http-proxybody-parser

node-http-proxy POST request times out


I am using node-http-proxy for the POST request as follows:

route.js
---------

var express = require('express');
var httpProxy = require('http-proxy');
var bodyParser = require('body-parser');
var proxy = httpProxy.createProxyServer({secure:false});
var jsonParser = bodyParser.json();

proxy.on('proxyReq', function(proxyReq, req, res, options) {
    logger.debug("proxying for",req.url);
    //set headers
    logger.debug('proxy request forwarded succesfully');
});

proxy.on('error', function (err, req, res) {
  res.writeHead(500, {
    'Content-Type': 'text/plain'
  });
  res.end('Something went wrong. And we are reporting a custom error message.');
});

proxy.on('proxyRes', function (proxyRes, req, res) {
  console.log('RAW Response from the target', JSON.stringify(proxyRes.headers, true, 2));
});

module.exports = function(app){
  app.post('/recording',jsonParser,function(req,res){
    // update request body
    proxy.web(req, res, { target: <<host>>:<<port>>});
  });
}

app.js
---------

var express = require('express');
var app = express();
 require('./routes')(app);

app.listen(8080);
console.log("Demo server running");

I also use bodyparser middleware and it has a known issue as mentioned in Gitbug issue. So I tried adding this line as the last line in app.js

app.use(require('connect-restreamer')());

But still the POST request hangs and ultimately fails. How do I fix this ? Is there any alternatives for bodyparser ?


Solution

  • Try reversing the order of the bodyParser- and proxy middleware:

    module.exports = function(app){
      app.post('/recording', function(req,res){
        // update request body
        proxy.web(req, res, { target: <<host>>:<<port>>});
      }, jsonParser);
    }
    

    Think this issue is similar to: socket hang up error with nodejs.