문제

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?

도움이 되었습니까?

해결책

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:

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top