Koa-compress is not working

无人久伴 提交于 2019-12-12 03:27:17

问题


This is my code for embedding koa-compress middleware

app.use(compress({
    filter: function (content_type) {
        return /text/i.test(content_type)
    },
    threshold: 1,
    flush: require('zlib').Z_SYNC_FLUSH
}))

And following is my response sending code

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

When I hit the URL through CURL I get a simple plain text saying "Hello World" but I believe I should have I got a compressed string because CURL doesn't do decompression by default. And when I hit the same URL on ChromeBrowser, I get the error saying ERR_CONTENT_DECODING_FAILED

When I set content-encoding to gzip, koa-compress should have compressed my response text but it's somehow not doing so. Maybe I'm making some mistake but I don't know what?


回答1:


I just retested the whole process once again and I realised that my code was not working because I had manually set content-encoding, which I should not have set and it should be set by compression middleware itself. I was making mistakes in assuming that response should always be compressed. But what I realised now, after lots of research is that compression works only when the client sends a header with Accept-Encoding. If supported Accept-Encoding is gzip, the response will be compressed in gzip if it's deflate, the response shall be compressed in deflate form, and if it's not mentioned response shall be simple plain data. I was receiving plain text in curl because curl does not send Accept-Encoding in its default request, but when I sent curl request using following code

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

then I received the response in compressed form. So my code has been working for always. Just that I should NOT have set

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

If content-encoding is set, the module will not run and produce error so we don't have to explicitly set the content-encoding, it should be set by compression middleware depending on Accept-Encoding of the request.

So the correct code to response should be like following


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


来源:https://stackoverflow.com/questions/44622464/koa-compress-is-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!