node-http-proxy icon indicating copy to clipboard operation
node-http-proxy copied to clipboard

hanging POST requests

Open joeyAghion opened this issue 14 years ago • 37 comments

Hi, I'm using express and trying to proxy certain requests to a different server, as follows (simplified):

var httpProxy = require('http-proxy');
var apiProxy = new httpProxy.RoutingProxy();
...
app.all('/api/*', function(req, res){
  apiProxy.proxyRequest(req, res, {host: 'example.com', port: 9000});
});

...but POST requests to my server appear to just hang, and never arrive at the target server.

I'm working on a stripped-down-but-working example of this but thought I'd ask first. Has anyone seen this behavior, or are there good examples of node-http-proxy coexisting with express? Thanks!

joeyAghion avatar Jan 25 '12 19:01 joeyAghion

I believe your issue may be solved by using the buffer method. A very good explanation can be found here.

AvianFlu avatar Jan 25 '12 19:01 AvianFlu

@AvianFlu: Thanks for the buffer pointer, but this ended up being caused by express's body-parsing.

Instead of declaring the API route (for proxying) within express routes, I configured it as middleware and used it before express.bodyParser().

Some coffeescript of the solution:

httpProxy = require 'http-proxy'
routingProxy = new httpProxy.RoutingProxy()
apiProxy = (pattern, host, port) ->
  (req, res, next) ->
    if req.url.match(pattern)
      routingProxy.proxyRequest req, res, host: host, port: port
    else
      next()

app.configure ->
  @set 'views', 'app/templates'
  # ...
  @use apiProxy /\/api\/.*/, 'localhost', 3000
  @use express.bodyParser()
  # ...

joeyAghion avatar Jan 26 '12 21:01 joeyAghion

You're correct - express's body parsing turns the request stream into a regular object. The solution is either to buffer it, as I was suggesting, or to deal with the request before the parsing, as you ended up doing. Glad you figured it out!

AvianFlu avatar Jan 26 '12 22:01 AvianFlu

I ran into this problem too .. [email protected], [email protected], [email protected].

In my case, it turns out that http-proxy's buffer doesn't play well with connect's bodyParser middleware. The buffer is adding listeners for the 'data' and 'end' events to the request object so that it can re-emit them later (on a call to proxyRequest, e.g.). The bodyParser middleware is also adding listeners for the 'data' and 'end' events to the request object but they are never removed. So when re-emitted by the buffer, they're picked up a second time by the bodyParser.

This can result in JSON parse errors and "Can't render headers after they are sent to the client" exceptions (and probably other errors).

coldfire22x avatar Feb 16 '12 07:02 coldfire22x

For those having issues with this, I found that this information seemed a bit out of date or difficult to implement (too much so for me, at least), compared to using connect-restreamer. That approach is outlined in the middleware example for using the bodyParser: https://github.com/nodejitsu/node-http-proxy/blob/master/examples/middleware/bodyDecoder-middleware.js

eethann avatar Dec 07 '12 04:12 eethann

So, How to solve this problem?

ijse avatar Dec 30 '12 10:12 ijse

connect-restreamer worked for me. The last thing in my middle-ware is:

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

Then I have a can do the proxy request normally:

var httpProxy = require('http-proxy');
var routingProxy = new httpProxy.RoutingProxy();

app.get('/proxy/', function (req, res) {
  routingProxy.proxyRequest(req, res, {
    host : host,
    port : port
  });
});

Configuring the proxy as part of middleware before bodyParser (if this is an option for you) also worked for me.

I did not attempt the buffer solution.

cesutherland avatar Jan 14 '13 23:01 cesutherland

Also, simply not using the bodyParser also works (for anyone's future reference).

xixixao avatar May 23 '13 18:05 xixixao

This thread has helped me. Thanks everyone.

renatoargh avatar Jun 27 '13 22:06 renatoargh

Helpful, Thanks!

nicolazj avatar Jul 19 '13 04:07 nicolazj

For some reason, connect-restreamer didn't fix it for me.

If anyone wants yet another fix, I ended up just calling bodyParser manually. So the proxying worked since bodyParser is not in the middleware. The code looked like:

var connect = require('connect');
var bodyParser = connect.bodyParser();

...

app.post("/blah", function(req, res) {
    bodyParser(req, res, function() {
        // Now do something with req.body.thePostData
        ...
        res.send(200);
    });
});

andyfischer avatar Sep 13 '13 23:09 andyfischer

@andyfischer

Man, you saved my life!

fonini avatar Feb 06 '14 18:02 fonini

Thanks for that solution it works fine Just configure the proxy as part of middleware before bodyParser

tarek-salah avatar Oct 29 '14 15:10 tarek-salah

Restreamer works for me. I needed to leave bodyParser because my proxy was conditional upon the contents of the request body. Here is a working example authored by someone else:

https://github.com/nodejitsu/node-http-proxy/blob/master/examples/middleware/bodyDecoder-middleware.js

gdw2 avatar Nov 06 '14 17:11 gdw2

The example from bodyDecoder pointed out by @gdw2 does not work for me. I get

/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)

Using connect-restreamer results in the request continuing to hang.

I am using express instead of connect.

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

This may related to this issue however.

FoxxMD avatar Apr 14 '15 15:04 FoxxMD

@FoxxMD same behavior here

franck34 avatar Apr 20 '15 15:04 franck34

For those in the unfortunate position not being able to rearrange/remove the bodyparser middleware: I've added the snippet from the example bodyDecode middleware right before I use proxy.web(...) and it just werkz

[...]
req.removeAllListeners('data');
req.removeAllListeners('end');

process.nextTick(function () {
if(req.body) {
   req.emit('data', JSON.stringify(req.body));
}
req.emit('end');
});
proxyServer.web( [...] );
[...]

Hope that helps. This was really frustrating.

schumacher-m avatar Apr 28 '15 17:04 schumacher-m

restreamer didn't work for me. Only way I was able to get it working with routing is like this:

app.post '/api/*', (req, res)->
  r = new http.IncomingMessage()
  r.httpVersion = req.httpVersion
  r.method = req.method
  r.headers = req.headers
  delete r.headers['accept-encoding']
  r.url = req.url
  r.socket = req.socket
  body = JSON.stringify(req.body)
  r.body = body
  size = Buffer.byteLength(body, 'utf8')
  r.headers['content-type'] = "application/json;charset=UTF-8"
  r.headers['content-length'] = size
  buffer = {}
  buffer.pipe = (dest)->
    process.nextTick ->
      dest.write(body)
  proxy.web(r, res, {
    buffer: buffer
    target: "http://localhost:1600"
    proxyTimeout: 5000
  })

glebtv avatar Apr 30 '15 08:04 glebtv

@schumacher-m thanks for that snippet...works for me

darrinholst avatar May 19 '15 13:05 darrinholst

@schumacher-m BIG thanks for your tips. It works around the hang issue finally - after a whole day of debugging.

aidanbon avatar Jul 28 '15 23:07 aidanbon