提交 be7d3347 编写于 作者: K Konstantin Vyatkin 提交者: Yiyu He

chore: removes code duplication at handling HEAD method (#1400)

上级 f155785e
......@@ -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();
}
......
......@@ -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();
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册