0

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?

4

1 回答 1

2

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')
于 2017-06-21T09:01:41.997 回答