My returned data is not gzipped with connect.compr

2019-05-10 09:52发布

I am trying to use the connect.compress() middleware to gzip my responses to the client. I am able to partially get it to work but when I add my own response using res.end the response is no longer gzipped.

Gzipped responses:

app = connect()
      .use(connect.compress())
      .use(connect.query())
      .use(connect.json());

Not gzipped responses:

app = connect()
      .use(connect.compress())
      .use(connect.query())
      .use(connect.json())
      .use(function (req, res) {
        res.end('hello');
      });

I would like to be able to respond with my own message but still have the content gzipped.

2条回答
迷人小祖宗
2楼-- · 2019-05-10 10:02

I had the same problem with small HTTP response bodies. If the Content-Length of the response body < compress' threshold value (default is 1024 bytes), then the response will not be compressed, with no warning (see the source code).

The solution is disable the threshold.

app.use(connect.compress({ threshold: false }));

As a new player to Connect I would expect that APIs would document what default values would be in place (ie: not specifying a threshold value default to 1024 bytes). Personally I think that not specifying a threshold should default it to 0; I don't want a threshold otherwise I'd specify it in the config.

查看更多
Emotional °昔
3楼-- · 2019-05-10 10:16

Try replacing this:

res.end('hello');

with this:

res.end(new Buffer('hello', 'utf8'));

If that works, it's probably a bug in your version of the connect middleware.

查看更多
登录 后发表回答