From 16397a4be4d078662c6fe4fca64fbb1de5306a5f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jimmy=20W=C3=A4rting?= Date: Tue, 25 Jan 2022 03:07:15 +0100 Subject: [PATCH 1/2] fix: handle bom in text and json --- src/body.js | 6 +++--- test/response.js | 5 +++++ 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/body.js b/src/body.js index b0fe16bb2..714e27ec4 100644 --- a/src/body.js +++ b/src/body.js @@ -145,8 +145,8 @@ export default class Body { * @return Promise */ async json() { - const buffer = await consumeBody(this); - return JSON.parse(buffer.toString()); + const text = await this.text(); + return JSON.parse(text); } /** @@ -156,7 +156,7 @@ export default class Body { */ async text() { const buffer = await consumeBody(this); - return buffer.toString(); + return new TextDecoder().decode(buffer); } /** diff --git a/test/response.js b/test/response.js index 714cda1a6..34e39116c 100644 --- a/test/response.js +++ b/test/response.js @@ -77,6 +77,11 @@ describe('Response', () => { expect(res.headers.get('a')).to.equal('1'); }); + it('should decode responses containing BOM', async () => { + const json = await new Response('\uFEFF{"a":1}').json(); + expect(json.a).to.equal(1); + }); + it('should support text() method', () => { const res = new Response('a=1'); return res.text().then(result => { From 20ac9677fa44a25660f200bd7f4e6f10cb764e61 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jimmy=20W=C3=A4rting?= Date: Tue, 25 Jan 2022 03:13:35 +0100 Subject: [PATCH 2/2] add test for text and arraybuffer as well --- test/response.js | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/test/response.js b/test/response.js index 34e39116c..b5157623f 100644 --- a/test/response.js +++ b/test/response.js @@ -77,11 +77,21 @@ describe('Response', () => { expect(res.headers.get('a')).to.equal('1'); }); - it('should decode responses containing BOM', async () => { + it('should decode responses containing BOM to json', async () => { const json = await new Response('\uFEFF{"a":1}').json(); expect(json.a).to.equal(1); }); + it('should decode responses containing BOM to text', async () => { + const text = await new Response('\uFEFF{"a":1}').text(); + expect(text).to.equal('{"a":1}'); + }); + + it('should keep BOM when getting raw bytes', async () => { + const ab = await new Response('\uFEFF{"a":1}').arrayBuffer(); + expect(ab.byteLength).to.equal(10); + }); + it('should support text() method', () => { const res = new Response('a=1'); return res.text().then(result => {