【问题标题】:Koa-compress is not workingKoa-compress 不工作
【发布时间】:2017-06-19 04:51:46
【问题描述】:

这是我嵌入 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 应该已经压缩了我的响应文本,但不知何故它没有这样做。也许我犯了一些错误,但我不知道是什么?

【问题讨论】:

    标签: node.js koa koa2


    【解决方案1】:

    我刚刚重新测试了整个过程,我意识到我的代码不起作用,因为我手动设置了content-encoding,我不应该设置它,它应该由压缩中间件本身设置。我在假设应始终压缩响应时犯了错误。但是我现在意识到,经过大量研究后,压缩仅在客户端发送带有Accept-Encoding 的标头时才有效。如果支持的Accept-Encoding为gzip,则响应为deflate,则将响应压缩为gzip,响应压缩为deflate形式,如果未提及,则响应为简单明文数据。我在 curl 中收到纯文本,因为 curl 在其默认请求中不发送 Accept-Encoding,但是当我使用以下代码发送 curl 请求时

    curl -H 'Accept-Encoding: gzip' -D - http://localhost:3000 
    

    然后我收到了压缩形式的回复。所以我的代码一直在工作。只是我不应该设置了

    ctx.set('content-encoding', 'gzip')

    如果设置了content-encoding,模块将不会运行并产生错误 所以我们不必显式设置内容编码,它应该由压缩中间件根据请求的Accept-Encoding设置。

    所以正确的响应代码应该如下所示


    ctx.body = 'Hello world'
    ctx.compress = true
    ctx.set('Content-Type', 'text/plain')
    

    【讨论】:

      猜你喜欢
      • 2018-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-25
      • 2019-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多