diff --git a/.changeset/eight-cooks-clap.md b/.changeset/eight-cooks-clap.md new file mode 100644 index 000000000..1ac1e300c --- /dev/null +++ b/.changeset/eight-cooks-clap.md @@ -0,0 +1,5 @@ +--- +'@lion/ajax': patch +--- + +fetchJSON will try to parse Response body as JSON if the content-type headers are missing, in this case it will assume JSON. diff --git a/packages/ajax/src/Ajax.js b/packages/ajax/src/Ajax.js index 4ea967bc5..bce865dd6 100644 --- a/packages/ajax/src/Ajax.js +++ b/packages/ajax/src/Ajax.js @@ -193,7 +193,10 @@ export class Ajax { /** @type {any} */ let body = responseText; - if (response.headers.get('content-type')?.includes('json')) { + if ( + !response.headers.get('content-type') || + response.headers.get('content-type')?.includes('json') + ) { try { body = JSON.parse(responseText); } catch (error) { diff --git a/packages/ajax/test/Ajax.test.js b/packages/ajax/test/Ajax.test.js index 2ab260383..2c7f46d32 100644 --- a/packages/ajax/test/Ajax.test.js +++ b/packages/ajax/test/Ajax.test.js @@ -166,6 +166,23 @@ describe('Ajax', () => { expect(response.body).to.eql('!@#$'); }); + it('tries to parse Response body as JSON if the content-type header is missing', async () => { + fetchStub.restore(); + fetchStub = stub(window, 'fetch'); + fetchStub.callsFake(() => { + const resp = new Response('{"a":1,"b":2}', { + headers: { + // eslint-disable-next-line no-plusplus + 'x-request-id': `${responseId++}`, + }, + }); + resp.headers.delete('content-type'); + return Promise.resolve(resp); + }); + const response = await ajax.fetchJson('/foo'); + expect(response.body).to.eql({ a: 1, b: 2 }); + }); + describe('given a request body', () => { it('encodes the request body as json', async () => { await ajax.fetchJson('/foo', { method: 'POST', body: { a: 1, b: 2 } });