【发布时间】:2014-10-27 12:36:12
【问题描述】:
我有一个 Node http-proxy 服务器正在做一些响应正文重写,基本上是这样做的:
- 客户端 GET localhost:8000/api/items
- 节点代理发送 localhost:8000 -> 到 example.com/api
- 服务器响应 json
[{ id: 1234, url: http://example.com/api/items/1234 }] - 节点代理将json重写为
[{ id: 1234, url: http://localhost:8000/api/items/1234 }] - 节点代理计算新的
content-length标头,设置它,并将响应返回给客户端
在后端服务器启用压缩之前,这一切正常。所以现在,默认情况下,响应被压缩。我通过在我的代理中设置这个来解决这个问题:
req.headers['accept-encoding'] = 'deflate';
所以在那之后,响应没有被压缩,我可以解析它们并根据需要重写正文。但是,这停止与 IE 一起工作。我认为问题在于响应仍然有一个transfer-encoding=chunked 标头,因此 IE 需要一个分块响应。因为存在 transfer-encoding 标头,所以没有 content-length 标头,即使我明确设置它(这两个标头是互斥的)。我已经尝试了我能想到的一切来删除 transfer-encoding 标头并获取 content-length 标头,但没有任何效果。我已经尝试了所有这些:
// In the context of my middleware response.writeHead function
res.setHeader('transfer-encoding', null);
res.setHeader('transfer-encoding', '');
res.removeHeader('transfer-encoding');
res.setHeader('content-length', modifiedBuffer.length); // this line alone worked before
res.originalWriteHead.call(res, statusCode, { 'Content-Length', modifiedBuffer.length });
// In the context of my middleware response.write function res.write(data, encoding)
// Here, encoding parameter is undefined
// According to docs, encoding defaults to utf8, could be 'chunked'
res.oldWrite.call(res, modifiedBuffer, 'utf8');
res.oldWrite.call(res, modifiedBuffer, '');
res.oldWrite.call(res, modifiedBuffer, null);
// tried all three previous the same for res.end
基本上,无论我做什么,响应都不会分块,而是设置了transfer-encoding 标头,而不是content-length。 Firefox、safari、chrome 似乎都可以很好地处理这个问题,但 IE 失败并出现错误XMLHttpRequest: Network Error 0x800c0007, No data is available for the requested resource.。这是(据我所知)因为它正在等待块(因为 transfer-encoding 标头),但得到响应的结尾,并且没有内容长度来读取它。
有谁知道我该如何解决这个问题?我在尝试删除 transfer-encoding 标头以支持 content-length 时做错了吗?
【问题讨论】:
-
你可能刚刚拯救了我的一周 :-)
标签: node.js middleware http-proxy