Node Express 内容长度 [英] Node Express Content-Length

查看:43
本文介绍了Node Express 内容长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 node.js 并在一个小项目中表达.我像打击一样设置响应头:

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

我可以使用console.log打印数据的长度是317.

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

但在浏览器的控制台,我只得到这些:

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

连接:保持连接
内容编码:gzip
内容类型:text/plain;charset=utf-8
日期:2013 年 6 月 1 日星期六 08:21:59 GMT
传输编码:分块
变化:接受编码
X-Powered-By:Express

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

那么,为什么 content-length 消失了?

So, why the content-length disappeared?

推荐答案

响应具有 Transfer-Encoding: chunked.这里 Content-Length 不适用,因为内容是在响应正文中的一个或多个部分(块)中发送的,带有一个标记来指示每个单独块的字节长度.http://en.wikipedia.org/wiki/Chunked_transfer_encoding

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 默认为 Transfer-Encoding: chunked.但是,这是通过在本机 http 响应对象上设置 Content-Length 标头来禁用的.HTTP 模块文档 说:

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:

发送Content-length"标头将禁用默认的分块编码.

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

根据响应中的 Content-Encoding:gzip 标头,您可能启用了 connect.compress 中间件.connect.compress 中间件删除了 Content-Length 标头.

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.

在任何情况下,除非您自己生成压缩内容,否则您自己生成的 Content-Length 标头肯定不适合最终(压缩)响应正文.幸运的是,connect 中间件会为您处理这些事情.

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.

在使用 Express 或 Connect 时,您不应假设您使用 res 对象发送"的内容实际上是以这种方式发送给客户端的.中间有中间件.所有中间件都能够更改有关响应的任何内容,包括更改响应正文,以及添加、删除和更改标头.请求也是如此.

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.

另见这些问题:

这篇关于Node Express 内容长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆