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 Content-Length entity-header field indicates the size of the entity-body, in decimal number of OCTETs, sent to the recipient or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET.
Node. js is a platform for building the i/o applications which are server-side event-driven and made using JavaScript. Express. js is a framework based on Node.
Two common full-stack JavaScript stacks are: MEAN stack - MongoDB (database), Express (server), Angular (front-end framework), and Node (runtime environment)
json() is a built-in middleware function in Express. This method is used to parse the incoming requests with JSON payloads and is based upon the bodyparser. This method returns the middleware that only parses JSON and only looks at the requests where the content-type header matches the type option.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With