diff --git a/History.md b/History.md index e9dfe33d7..1905e22f8 100644 --- a/History.md +++ b/History.md @@ -13,6 +13,7 @@ ## Fixes - fix: Do not response Content-Length if Transfer-Encoding is defined #1562 @charlyzeng +- fix: Set body to `null` if `ctx.type = json` and `ctx.body = null` #1059 @likegun 2.13.1 / 2021-01-04 ================== diff --git a/__tests__/response/length.js b/__tests__/response/length.js index 1e58f42a4..7ca9ef891 100644 --- a/__tests__/response/length.js +++ b/__tests__/response/length.js @@ -27,6 +27,9 @@ describe('res.length', () => { it('should return a number', () => { const res = response() + res.body = null + assert.strictEqual(res.length, undefined) + res.body = 'foo' res.remove('Content-Length') assert.strictEqual(res.length, 3) @@ -63,4 +66,16 @@ describe('res.length', () => { }) }) }) + + describe('and a .type is set to json', () => { + describe('and a .body is set to null', () => { + it('should return a number', () => { + const res = response() + + res.type = 'json' + res.body = null + assert.strictEqual(res.length, 4) + }) + }) + }) }) diff --git a/lib/response.js b/lib/response.js index 8546c632b..d15ecd5c2 100644 --- a/lib/response.js +++ b/lib/response.js @@ -137,7 +137,13 @@ module.exports = { // no content if (val == null) { - if (!statuses.empty[this.status]) this.status = 204 + if (!statuses.empty[this.status]) { + if (this.type === 'application/json') { + this._body = 'null' + return + } + this.status = 204 + } if (val === null) this._explicitNullBody = true this.remove('Content-Type') this.remove('Content-Length')