diff --git a/lib/application.js b/lib/application.js index e5a6b76..39e8a08 100644 --- a/lib/application.js +++ b/lib/application.js @@ -5,6 +5,7 @@ var debug = require('debug')('koa:application'); var onFinished = require('finished'); var Emitter = require('events').EventEmitter; +var Stream = require('stream'); var compose = require('koa-compose'); var context = require('./context'); var request = require('./request'); @@ -174,7 +175,6 @@ function *respond(next) { var body = this.body; var code = this.status = this.status || 404; - var head = 'HEAD' == this.method; // ignore body if (status.empty[code]) { @@ -183,10 +183,12 @@ function *respond(next) { return res.end(); } - if (null == body) { - // empty body - if (head) return res.end(); + if ('HEAD' == this.method) { + if (isJSON(body)) this.length = Buffer.byteLength(JSON.stringify(body)); + return res.end(); + } + if (null == body) { // status body this.type = 'text'; body = status[code]; @@ -195,27 +197,29 @@ function *respond(next) { } // Buffer body - if (Buffer.isBuffer(body)) { - if (head) return res.end(); - return res.end(body); - } + if (Buffer.isBuffer(body)) return res.end(body); // string body - if ('string' == typeof body) { - if (head) return res.end(); - return res.end(body); - } + if ('string' == typeof body) return res.end(body); // Stream body - if ('function' == typeof body.pipe) { - if (head) return res.end(); - - return body.pipe(res); - } + if (body instanceof Stream) return body.pipe(res); // body: json body = JSON.stringify(body); this.length = Buffer.byteLength(body); - if (head) return res.end(); res.end(body); } + +/** + * Check if `body` should be interpreted as json. + * + */ + +function isJSON(body) { + if (!body) return false; + if ('string' == typeof body) return false; + if (body instanceof Stream) return false; + if (Buffer.isBuffer(body)) return false; + return true; +} diff --git a/test/application.js b/test/application.js index 2acc1d7..962b09f 100644 --- a/test/application.js +++ b/test/application.js @@ -156,12 +156,34 @@ describe('app.respond', function(){ .expect(200) .end(function(err, res){ if (err) return done(err); + res.should.have.header('Content-Type', 'text/plain; charset=utf-8'); res.should.have.header('Content-Length', '5'); assert(0 == res.text.length); done(); }); }) + it('should keep the headers', function(done){ + var app = koa(); + + app.use(function *(){ + this.body = { hello: 'world' }; + }); + + var server = app.listen(); + + request(server) + .head('/') + .expect(200) + .end(function(err, res){ + if (err) return done(err); + res.should.have.header('Content-Type', 'application/json'); + res.should.have.header('Content-Length', '17'); + assert(0 == res.text.length); + done(); + }); + }) + it('should respond with a 404 if no body was set', function(done){ var app = koa();