POST proxying with bodyParser middleware
Created by: thisiskarthikj
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.