diff --git a/docs/api/index.md b/docs/api/index.md index a0e787b..fa77426 100644 --- a/docs/api/index.md +++ b/docs/api/index.md @@ -126,7 +126,7 @@ http.createServer(app.callback()).listen(3001); ## app.use(function) - Add the given middleware function to this application. See [Middleware](#middleware) for + Add the given middleware function to this application. See [Middleware](https://github.com/koajs/koa/wiki#middleware) for more information. ## app.keys= diff --git a/lib/application.js b/lib/application.js index be1a6b2..89e575c 100644 --- a/lib/application.js +++ b/lib/application.js @@ -181,9 +181,11 @@ function *respond(next){ this.status = 200; if (this.app.poweredBy) this.set('X-Powered-By', 'koa'); - yield next; + yield *next; var res = this.res; + if (res.headersSent || !res.socket.writable) return; + var body = this.body; var head = 'HEAD' == this.method; var noContent = ~[204, 205, 304].indexOf(this.status); diff --git a/test/application.js b/test/application.js index 29c433b..073e484 100644 --- a/test/application.js +++ b/test/application.js @@ -134,6 +134,61 @@ describe('app.respond', function(){ }) }) + describe('when res has already been written to', function(){ + + it('should not cause an app error', function(done){ + var app = koa(); + + app.use(function *(next){ + var res = this.res; + res.setHeader("Content-Type", "text/html") + res.status = 200; + res.write('Hello'); + setTimeout(function () { + res.end("Goodbye") + }, 0); + }); + + var errorCaught = false; + + app.on('error', function (err) { + errorCaught = err; + }); + + var server = app.listen(); + + request(server) + .get('/') + .expect(200) + .end(function(err, res){ + if (err) return done(err); + if (errorCaught) return done(errorCaught); + done(); + }); + }) + + it('should send the right body', function(done){ + var app = koa(); + + app.use(function *(next){ + var res = this.res; + res.setHeader("Content-Type", "text/html") + res.status = 200; + res.write('Hello'); + setTimeout(function () { + res.end("Goodbye") + }, 0); + }); + + var server = app.listen(); + + request(server) + .get('/') + .expect(200) + .expect('HelloGoodbye', done); + }) + }) + describe('when .body is missing', function(){ describe('with status=400', function(){ it('should respond with the associated status message', function(done){