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