node.js - 为什么无法删除 Node 代理中的传输编码 header ?

标签 node.js middleware http-proxy

我有一个 Node http-proxy 服务器进行一些响应正文重写,基本上是这样做的:

  1. 客户端 GET localhost:8000/api/items
  2. Node 代理发送 localhost:8000 -> 到 example.com/api
  3. 服务器以 json 响应[{ id: 1234, url: http://example.com/api/items/1234 }]
  4. Node 代理将 json 重写为 [{ id: 1234, url: http://localhost:8000/api/items/1234 }]
  5. Node 代理计算新的 content-length header ,设置它,并将响应返回给客户端

在后端服务器启用压缩之前,这一切都工作正常。所以现在,默认情况下,响应被压缩。我通过在我的代理中设置它来解决这个问题:

req.headers['accept-encoding'] = 'deflate';

因此,在那之后,响应没有被压缩,我可以解析它们并根据需要重写正文。然而,这在 IE 中停止工作。我认为问题在于响应仍然有一个 transfer-encoding=chunked header ,因此 IE 需要一个分块响应。由于存在 transfer-encoding header ,因此没有 content-length header ,即使我显式设置它(这两个 header 是互斥的)。我已经尝试了所有我能想到的方法来删除 transfer-encoding header 并获取 content-length header ,但没有任何效果。我已经尝试过所有这些:

// 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 header ,而不是 content-length。 Firefox、safari、chrome 似乎都能很好地处理这个问题,但 IE 会失败,并出现错误 XMLHttpRequest: Network Error 0x800c0007, No data is available for the requested resources.。这是(据我所知)因为它正在等待 block (由于 transfer-encoding header ),但获得了响应的结尾,并且没有内容长度来读取它。

有谁知道我该如何解决这个问题吗?我尝试删除 transfer-encoding header 以支持 content-length 时是否做错了什么?

最佳答案

我自己解决了这个问题:

我有效地使用了两个中间件组件(我自己的,在问题中描述的)和express.js 压缩。我的中间件正在解压缩响应,但压缩可确保响应始终使用 transfer-encoding=chunked 写入,并删除 content-length

删除express.js压缩模块为我解决了这个问题。

关于node.js - 为什么无法删除 Node 代理中的传输编码 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26587731/

相关文章:

node.js - 复制大文件(超过 2GB)时出现 Node 未知系统错误

javascript - 如何在 Node.js Express 的 async.each 中使用 request

python - 被中间件执行过程迷惑,DJANGO

c# - 从身份验证中排除文件类型的中间件

ssl - Heroku SSL Endpoint 附加组件的替代品

javascript - 如何在 PyV8 中加载 Nodejs 模块?

node.js - Angular universal 正在为每个页面在页面源中呈现主页 html

node.js - 在 express 中,当我调用next(err)时,下一个订单号/中间件不会被调用/处理

ant - 如何覆盖 Jenkins 中的 http_proxy 环境变量?

Android SDK Manager : Bug when connecting to a proxy (empty username), 你能确认吗?