未验证 提交 8d52105a 编写于 作者: E ejose19 提交者: GitHub

feat: allow bodyless responses for non empty status codes (#1447)

Co-authored-by: NEladio Mora <eladio@atlasmarket.io>
上级 6b6b0ddf
......@@ -238,6 +238,11 @@ function respond(ctx) {
// status body
if (null == body) {
if (ctx.response._explicitNullBody) {
ctx.response.remove('Content-Type');
ctx.response.remove('Transfer-Encoding');
return res.end();
}
if (ctx.req.httpVersionMajor >= 2) {
body = String(code);
} else {
......
......@@ -139,6 +139,7 @@ module.exports = {
// no content
if (null == val) {
if (!statuses.empty[this.status]) this.status = 204;
if (val === null) this._explicitNullBody = true;
this.remove('Content-Type');
this.remove('Content-Length');
this.remove('Transfer-Encoding');
......
......@@ -810,4 +810,41 @@ describe('app.respond', () => {
assert.equal(res.headers.hasOwnProperty('content-type'), false);
});
});
describe('with explicit null body', () => {
it('should preserve given status', async() => {
const app = new Koa();
app.use(ctx => {
ctx.body = null;
ctx.status = 404;
});
const server = app.listen();
return request(server)
.get('/')
.expect(404)
.expect('')
.expect({});
});
it('should respond with correct headers', async() => {
const app = new Koa();
app.use(ctx => {
ctx.body = null;
ctx.status = 401;
});
const server = app.listen();
const res = await request(server)
.get('/')
.expect(401)
.expect('')
.expect({});
assert.equal(res.headers.hasOwnProperty('content-type'), false);
});
});
});
......@@ -10,6 +10,8 @@ describe('app.response', () => {
app1.response.msg = 'hello';
const app2 = new Koa();
const app3 = new Koa();
const app4 = new Koa();
const app5 = new Koa();
it('should merge properties', () => {
app1.use((ctx, next) => {
......@@ -43,4 +45,30 @@ describe('app.response', () => {
.expect(404);
assert.equal(response.text, '404');
});
it('should set ._explicitNullBody correctly', async() => {
app4.use((ctx, next) => {
ctx.body = null;
assert.strictEqual(ctx.response._explicitNullBody, true);
});
return request(app4.listen())
.get('/')
.expect(204);
});
it('should not set ._explicitNullBody incorrectly', async() => {
app5.use((ctx, next) => {
ctx.body = undefined;
assert.strictEqual(ctx.response._explicitNullBody, undefined);
ctx.body = '';
assert.strictEqual(ctx.response._explicitNullBody, undefined);
ctx.body = false;
assert.strictEqual(ctx.response._explicitNullBody, undefined);
});
return request(app5.listen())
.get('/')
.expect(204);
});
});
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册