diff --git a/lib/response.js b/lib/response.js index 8d94546..01c5c1d 100644 --- a/lib/response.js +++ b/lib/response.js @@ -534,6 +534,6 @@ module.exports = { * Flush any set headers, and begin the body */ flushHeaders() { - this.res.writeHead(this.res.statusCode); + this.res.flushHeaders(); } }; diff --git a/test/response/flushHeaders.js b/test/response/flushHeaders.js index 427f2ff..e23a2fc 100644 --- a/test/response/flushHeaders.js +++ b/test/response/flushHeaders.js @@ -4,6 +4,7 @@ const request = require('supertest'); const assert = require('assert'); const Koa = require('../..'); +const http = require('http'); describe('ctx.flushHeaders()', () => { it('should set headersSent', done => { @@ -95,4 +96,43 @@ describe('ctx.flushHeaders()', () => { done(err); }); }); + + it('should flush headers first and delay to send data', done => { + const PassThrough = require('stream').PassThrough; + const app = new Koa(); + + app.use(ctx => { + ctx.type = 'json'; + ctx.status = 200; + ctx.headers['Link'] = '; as=style; rel=preload, ; rel=preconnect; crossorigin'; + const stream = ctx.body = new PassThrough(); + ctx.flushHeaders(); + + setTimeout(() => { + stream.end(JSON.stringify({ message: 'hello!' })); + }, 10000); + }); + + app.listen(function(err){ + if (err) return done(err); + + const port = this.address().port; + + http.request({ + port + }) + .on('response', res => { + const onData = () => done(new Error('boom')); + res.on('data', onData); + + // shouldn't receive any data for a while + setTimeout(() => { + res.removeListener('data', onData); + done(); + }, 1000); + }) + .on('error', done) + .end(); + }); + }); });