Node Express Content-Length

2019-02-03 05:54发布

问题:

I use node.js and express at a small project. I set response header like blow:

res.set({'Content-Type':'text/plain;charset=utf-8',    
'Content-Length': Buffer.byteLength(data, 'utf-8')});       

I can use console.log print data's length is 317.

But at browser's console, I just get these:

Connection:keep-alive
Content-Encoding:gzip
Content-Type:text/plain;charset=utf-8
Date:Sat, 01 Jun 2013 08:21:59 GMT
Transfer-Encoding:chunked
Vary:Accept-Encoding
X-Powered-By:Express

So, why the content-length disappeared?

回答1:

The response has Transfer-Encoding: chunked. Here Content-Length is not applicable, because the content is sent in one or more parts (chunks) inside the response body, with a marker indicating the byte-length of each individual chunk. http://en.wikipedia.org/wiki/Chunked_transfer_encoding

Node.js defaults to Transfer-Encoding: chunked. However, this is disabled by setting the Content-Length header on the native http response object. Documentation of HTTP module says:

Sending a 'Content-length' header will disable the default chunked encoding.

Going by the Content-Encoding:gzip header in your response, you probably have enabled the connect.compress middleware. The connect.compress middleware removes the Content-Length header.

In any case, unless you are generating gzipped content yourself, the Content-Length header you generate yourself would surely be inappropriate for the final (gzipped) response body. Luckily, the connect middleware takes care of that for you.

When using Express or Connect, you should not assume that the things you "send" with the res object actually get sent that way to the client. There's middleware in between. All middleware has the ability to change just about anything about the response, including changing the response body, and adding, removing and changing headers. Same goes for the request.

See also these questions:

  • Chunked encoding and content-length header
  • HTTP Chunked data size and content length