【问题标题】:How to disable response data compression in Express?如何在 Express 中禁用响应数据压缩?
【发布时间】:2021-09-09 00:39:41
【问题描述】:

我想收到来自服务器“Content-Length”的响应 为此,我想禁用 gzip 压缩。我用于此压缩中间件:

const shouldCompress = (req, res) => {
    if(req.headers['x-no-comprassion']) {
        return false
    } 
}

app.use(compression({threshold: 5, filter: shouldCompress}))

并且还从客户端发送“x-no-compassion”标头,但它仍然不起作用。 可能是什么问题?

【问题讨论】:

    标签: javascript express server


    【解决方案1】:

    content-length 在发送响应时由 express api 自动发送: https://github.com/expressjs/express/blob/28db2c2c5cf992c897d1fbbc6b119ee02fe32ab1/lib/response.js#L194.

    压缩激活与否,这个标头应该存在。

    【讨论】:

    • 但他不在响应中
    • 只有在响应不包含标头“内容编码”时才会出现长度。响应未编码时,响应中出现长度
    【解决方案2】:

    我已经用这段代码测试过:

    const compression = require('compression');
    const express = require('express');
    const app = express();
    
    function shouldCompress(req, res) {
      if (req.headers['x-no-compression']) return false;
      return compression.filter(req, res);
    }
    
    app.use(compression({threshold: 5, filter: shouldCompress}));
    app.get('/', function (req, res) { res.json({state: "ok"}); });
    app.listen(8888, () => { console.log(`Started http://localhost:8888`) });
    

    当我启动时 curl localhost:8888 -v
    => 我有:Content-Length: 14

    当我启动时 curl localhost:8888 -v -H 'Accept-Encoding: gzip, deflate'
    => 响应中没有内容长度,并且是二进制输出 Warning: Binary output can mess up your terminal.

    当我启动时 curl localhost:8888 -v -H 'Accept-Encoding: gzip, deflate' -H 'x-no-compression: 1'
    => 我有:Content-Length: 14

    所以,没有问题,它可以正常工作。 你是如何发送标题的?你设置了值吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-29
      • 2013-12-07
      • 2013-11-02
      • 1970-01-01
      • 1970-01-01
      • 2013-03-01
      • 2010-12-13
      • 1970-01-01
      相关资源
      最近更新 更多