diff --git a/lib/application.js b/lib/application.js index 6415444da..46f43134e 100644 --- a/lib/application.js +++ b/lib/application.js @@ -10,7 +10,6 @@ const debug = require('debug')('koa:application'); const onFinished = require('on-finished'); const response = require('./response'); const compose = require('koa-compose'); -const isJSON = require('koa-is-json'); const context = require('./context'); const request = require('./request'); const statuses = require('statuses'); @@ -225,9 +224,10 @@ function respond(ctx) { return res.end(); } - if ('HEAD' == ctx.method) { - if (!res.headersSent && isJSON(body)) { - ctx.length = Buffer.byteLength(JSON.stringify(body)); + if ('HEAD' === ctx.method) { + if (!res.headersSent && !ctx.response.has('Content-Length')) { + const { length } = ctx.response; + if (Number.isInteger(length)) ctx.length = length; } return res.end(); } diff --git a/package.json b/package.json index ef301c216..708e89133 100644 --- a/package.json +++ b/package.json @@ -40,7 +40,6 @@ "is-generator-function": "^1.0.7", "koa-compose": "^4.1.0", "koa-convert": "^1.2.0", - "koa-is-json": "^1.0.0", "on-finished": "^2.3.0", "only": "~0.0.2", "parseurl": "^1.3.2", diff --git a/test/application/respond.js b/test/application/respond.js index 14f13211d..d254ead6e 100644 --- a/test/application/respond.js +++ b/test/application/respond.js @@ -173,6 +173,26 @@ describe('app.respond', () => { assert(!res.text); }); + it('should keep stream header if set manually', async() => { + const app = new Koa(); + + const { length } = fs.readFileSync('package.json'); + + app.use(ctx => { + ctx.length = length; + ctx.body = fs.createReadStream('package.json'); + }); + + const server = app.listen(); + + const res = await request(server) + .head('/') + .expect(200); + + assert.equal(res.header['content-length'], length); + assert(!res.text); + }); + it('should respond with a 404 if no body was set', () => { const app = new Koa();