Node-http-proxy: POST proxying with bodyParser middleware

Created on 10 Feb 2016  路  3Comments  路  Source: http-party/node-http-proxy

The following is my code.

route.js

var express = require('express');
var httpProxy = require('http-proxy');
var bodyParser = require('body-parser');
var proxy = httpProxy.createProxyServer({secure:false});
var app = express();
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");

But still the POST request hangs and ultimately fails.

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

I also tried restreamer code but I get the following error if I use the restreamer

error: uncaughtException: Can't set headers after they are sent.
I get this error because I emit end in the restreamer and then try to set the headers in proxy.on function. Any suggestions appreciated.

Most helpful comment

@karthikus How did you work around the issue?

All 3 comments

I manage to work around the issue. But now I am facing an unique issue. The content seems to be truncated when the request is proxied to the server. I tried setting content-length to the body length and it does not work. Any suggestions ?

It maybe be how you are measuring the length. That is the encoding may throw that off. I don鈥檛 think you need have a content-length specified. If not, just take the header out altogether. Also, make sure it is actually getting set. Validate that the destination server actually gets the header with the length you set. What I think is happening for you in the bodyParser middleware is mutating the content, and thus the length, before it goes to the destination server.

@karthikus How did you work around the issue?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

miton18 picture miton18  路  5Comments

martindale picture martindale  路  6Comments

sisyphsu picture sisyphsu  路  3Comments

jsmylnycky picture jsmylnycky  路  3Comments

mohammad-goldast picture mohammad-goldast  路  3Comments