Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: handle bom in text and json #1482

Merged
merged 2 commits into from Mar 11, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 3 additions & 3 deletions src/body.js
Expand Up @@ -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);
}

/**
Expand All @@ -156,7 +156,7 @@ export default class Body {
*/
async text() {
const buffer = await consumeBody(this);
return buffer.toString();
return new TextDecoder().decode(buffer);
}

/**
Expand Down
15 changes: 15 additions & 0 deletions test/response.js
Expand Up @@ -77,6 +77,21 @@ describe('Response', () => {
expect(res.headers.get('a')).to.equal('1');
});

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 => {
Expand Down