使用Node.JS提供HTTP / 1.0响应(未知内容长度,分块传输编码)
我通过Node.JS提供未知长度的资源。因此,无法设置 Content-Length
标头。对于HTTP 1.1,要求将chunked编码用于此类资源。 Node.JS知道这一点并使用chunked transfer encoding自行发送我的数据,并带有以下标题:
I am serving a resource of unknown length via Node.JS. Because of this, the Content-Length
header cannot be set. For HTTP 1.1, it is required that chunked encoding is used for resources of this nature. Node.JS knows this and sends my data with chunked transfer encoding all on its own, with the following headers:
HTTP/1.1 200 OK
Transfer-Encoding: chunked
Connection: close
...
这对于表现良好的客户来说都很好。 但是,我必须支持一些表现不佳的客户端(即Android 2.2及更早版本)。这些客户端不支持正确的分块传输编码。
This is all fine and good for well-behaved clients. However, I have some not-so-well behaved clients (namely Android 2.2 and earlier) that I must support. These clients do not support chunked transfer encoding properly.
我最初的想法是将编码设置为无
,如下所示:
My initial thought was set the encoding to none
like so:
response.writeHead(200, {'Transfer-Encoding': 'none'});
这会禁用Node.JS的自动分块编码并保持与大多数客户端的兼容性。但是,现在我已经破坏了Android 2.3+客户端,因为当他们看到这样一个伪造的传输编码头时,他们只是咳嗽和窒息。
This disables Node.JS's automatic chunked encoding and maintains compatibility with most clients. However, now I have broken Android 2.3+ clients, as they simply cough and choke when they see such a bogus transfer encoding header.
当我使用 HTTP / 1.0
发出请求时,服务器正确地返回没有分块编码的响应:
When I make requests with HTTP/1.0
, the server properly returns the response without chunked encoding:
HTTP/1.1 200 OK
Connection: close
...
这解决了我的问题,并允许我提供适用于我所有麻烦客户的流。我不必为 Transfer-Encoding
发送虚假标题,我仍然不必指定内容的持续时间。
This solves my problem, and allows me to serve a stream that works for all of my troublesome clients. I don't have to send a bogus header for Transfer-Encoding
, and I still don't have to specify how long the content is.
如何强制Node.JS的HTTP服务器始终以HTTP / 1.0模式运行?
以正确的方式强制非分块响应
有一种支持的关闭分块编码的方法:你只需删除 request.removeHeader(name)c $ c> Transfer-Encoding 标头:
response.removeHeader('transfer-encoding');
无论如何,Node.js都会尊重。甚至还有测试,以防止有人意外改变这种行为,所以我认为这是非常安全的。
Node.js will respect no matter what. There's even a test to prevent someone from accidentally changing this behavior, so I think it's pretty safe to use.
所以你可以坚持尝试#1 ,但如上所述。
So you can just stick with attempt #1, but doing it as described above.