Koa-compress 不工作
Koa-compress is not working
这是我嵌入koa-compress中间件的代码
app.use(compress({
filter: function (content_type) {
return /text/i.test(content_type)
},
threshold: 1,
flush: require('zlib').Z_SYNC_FLUSH
}))
下面是我的回复发送码
ctx.body = 'Hello world'
ctx.compress = true
ctx.set('Content-Type', 'text/plain')
ctx.set('content-encoding', 'gzip')
当我通过 CURL 点击 URL 时,我得到一个简单的纯文本 "Hello World" 但我相信我应该得到一个压缩字符串,因为 CURL 默认不解压。当我在 ChromeBrowser 上点击相同的 URL 时,我收到错误提示 ERR_CONTENT_DECODING_FAILED
当我将内容编码设置为 gzip 时,koa-compress 应该压缩了我的响应文本,但不知何故没有这样做。也许我犯了一些错误,但我不知道是什么?
我刚刚再次测试了整个过程,我意识到我的代码无法正常工作,因为我手动设置了 content-encoding
,我不应该设置它,它应该由压缩中间件本身设置。我在 假设 应始终压缩响应时犯了错误。但我现在意识到,经过大量研究后,只有当客户端发送 header 和 Accept-Encoding
时,压缩才会起作用。如果支持Accept-Encoding是gzip
,如果是deflate
,响应将以gzip压缩,如果是deflate
,响应将以deflate
形式压缩,如果没有提到响应将是简单的纯数据。我在 curl 中收到纯文本,因为 curl 在其默认请求中不发送 Accept-Encoding
,但是当我使用以下代码发送 curl 请求时
curl -H 'Accept-Encoding: gzip' -D - http://localhost:3000
然后我收到了压缩格式的回复。所以我的代码一直在工作。只是我不应该设置
ctx.set('content-encoding', 'gzip')
如果设置了content-encoding
,模块不会运行而报错
所以我们不必显式设置 content-encoding,它应该由压缩中间件根据请求的 Accept-Encoding
设置。
所以正确的响应代码应该如下所示
ctx.body = 'Hello world'
ctx.compress = true
ctx.set('Content-Type', 'text/plain')
这是我嵌入koa-compress中间件的代码
app.use(compress({
filter: function (content_type) {
return /text/i.test(content_type)
},
threshold: 1,
flush: require('zlib').Z_SYNC_FLUSH
}))
下面是我的回复发送码
ctx.body = 'Hello world'
ctx.compress = true
ctx.set('Content-Type', 'text/plain')
ctx.set('content-encoding', 'gzip')
当我通过 CURL 点击 URL 时,我得到一个简单的纯文本 "Hello World" 但我相信我应该得到一个压缩字符串,因为 CURL 默认不解压。当我在 ChromeBrowser 上点击相同的 URL 时,我收到错误提示 ERR_CONTENT_DECODING_FAILED
当我将内容编码设置为 gzip 时,koa-compress 应该压缩了我的响应文本,但不知何故没有这样做。也许我犯了一些错误,但我不知道是什么?
我刚刚再次测试了整个过程,我意识到我的代码无法正常工作,因为我手动设置了 content-encoding
,我不应该设置它,它应该由压缩中间件本身设置。我在 假设 应始终压缩响应时犯了错误。但我现在意识到,经过大量研究后,只有当客户端发送 header 和 Accept-Encoding
时,压缩才会起作用。如果支持Accept-Encoding是gzip
,如果是deflate
,响应将以gzip压缩,如果是deflate
,响应将以deflate
形式压缩,如果没有提到响应将是简单的纯数据。我在 curl 中收到纯文本,因为 curl 在其默认请求中不发送 Accept-Encoding
,但是当我使用以下代码发送 curl 请求时
curl -H 'Accept-Encoding: gzip' -D - http://localhost:3000
然后我收到了压缩格式的回复。所以我的代码一直在工作。只是我不应该设置
ctx.set('content-encoding', 'gzip')
如果设置了content-encoding
,模块不会运行而报错
所以我们不必显式设置 content-encoding,它应该由压缩中间件根据请求的 Accept-Encoding
设置。
所以正确的响应代码应该如下所示
ctx.body = 'Hello world'
ctx.compress = true
ctx.set('Content-Type', 'text/plain')