Luc
Luc

Reputation: 17072

NGINX + node.js with http-proxy => length added in header

I use node.js behind nginx.The node.js app uses http-proxy.
Basically, the request gets to nginx and is then proxied to the node app:

- if static files are requested, the node.js app serves them
- if non static files are requested, the node.js app proxyies the request to a second node.js app (using http-proxy npm).

The second case works perfectly when nginx is not in the picture. When nginx is added, the response is quite strange: it's surrounded with strange stuff:

"4c\r\n{ json stuff }\r\n0"

instead of

{ json stuff }

To summarize:

  1. (without nginx): request for dynamic content -> node.js -> proxy to another node.js app -> response sent back to the user is correct: { json stuff }

  2. (with nginx): request for dynamic content -> node.js -> proxy to another node.js app -> response sent back to the user is not correct: "4c\r\n{ json stuff }\r\n0"

I still don't understand what's going on here... any idea ?

UPDATE

Hmmm.... seems like it's linked to nginx adding additional header to the request...

My nginx conf is:

upstream my_sock {
   server unix:/tmp/test.sock
   fail_timeout=0;
}
server {
   listen 8099;
   client_max_body_size 4G;
   server_name localhost;

   keepalive_timeout 5;

   location / {
     proxy_pass http://my_sock;
     proxy_redirect off;
     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
     proxy_set_header Host $http_host;
   }
}

Any idea how to remove those additional headers ?

UPDATE 2

the 4c added seems to be the length of the response I expect (json stuff). I then added:

proxy_set_header Content-Length '';

in nginx conf but nothing changed... I still have the 4c displayed... Arg...

Upvotes: 2

Views: 2139

Answers (1)

Benjie
Benjie

Reputation: 7946

I know it's been 6 months, so you probably already know this, but in case someone else finds your question:

This is nginx outputting a chunked transfer encoding (Transfer-Encoding: chunked) - as you correctly stated the 4c is the length of the next chunk (in hex), and the 0 at the end (also hex) states there's nothing more coming (i.e. it's the end of the transfer). This will be misinterpreted by the browser/client if it doesn't also include the Transfer-Encoding: chunked header - I'd check this first.

NodeJS defaults to chunked encoding unless you explicitly set the Content-Length header. I don't have much experience with nginx but my guess is that if your NodeJS code outputs the Content-Length header correctly then nginx should forward this unless you tell it otherwise - so I'd check your NodeJS server's headers. You might also try updating your nginx - I have a vague recollection that earlier versions don't handle chunked transfer encoding very well, though I may be mistaken.

Upvotes: 3

Related Questions