I've also posted this to the relevant issue on http-proxy
.
I'm using http-proxy
with express
so I can intercept requests between my client and api in order to add some cookies for authentication.
In order to authenticate the client must send a POST request with x-www-form-urlencoded
as the the content-type. So I am using body-parser
middleware to parse the request body so I can insert data in the request.
http-proxy
has a problem with using body-parser
supposedly because it parses the body as a stream and never closes it so the proxy never never completes the request.
There is a solution in the http-proxy examples that "re-streams" the request after it has been parsed which I have tried to use. I have also tried to use the connect-restreamer
solution in the same issue with no luck.
My code looks like this
var express = require('express'),
bodyParser = require('body-parser'),
httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer({changeOrigin: true});
var restreamer = function (){
return function (req, res, next) { //restreame
req.removeAllListeners('data')
req.removeAllListeners('end')
next()
process.nextTick(function () {
if(req.body) {
req.emit('data', req.body) //error gets thrown here
}
req.emit('end')
})
}
}
var app = express();
app.use(bodyParser.urlencoded({extended: false, type: 'application/x-www-form-urlencoded'}));
app.use(restreamer());
app.all("/api/*", function(req, res) {
//modifying req.body here
//
proxy.web(req, res, { target: 'http://urlToServer'});
});
app.listen(8080);
and I receive this error
/Code/project/node_modules/http-proxy/lib/http-proxy/index.js:119
throw err;
^
Error: write after end
at ClientRequest.OutgoingMessage.write (_http_outgoing.js:413:15)
at IncomingMessage.ondata (_stream_readable.js:540:20)
at IncomingMessage.emit (events.js:107:17)
at /Code/project/lib/server.js:46:25
at process._tickCallback (node.js:355:11)
I have tried to debug the flow but am grasping for straws. Any suggestions please??