fix: Do not response Content-Length if Transfer-Encoding is defined by charlyzeng · Pull Request #1562 · koajs/koa (original) (raw)

Background

Nodejs http module can not handle response that contains both Content-Length and Transfer-Encoding header, you can see it at https://github.com/nodejs/node/blob/v16.6.1/deps/llhttp/src/llhttp.c#L5811.

Problem

Koa will auto set Content-Length response header when use ctx.body = ..., but if Transfer-Encoding response header is defined, Content-Length should not be set. Otherwise, the response can not be handled by nodejs http module.

How To Appear

// server.js const Koa = require('koa');

const app = new Koa(); app.use((ctx) => { ctx.set('Transfer-Encoding', 'chunked'); ctx.body = 'hello world'; }); app.listen(9000);

// client.js const http = require('http');

http.get('http://127.0.0.1:9000');

As above, run node server.js to start server, then run node client.js to send a request. Finally, you'll get an error as follow:
image

How To Resolve

Don't set Content-Length header if Transfer-Encoding is defined.