fix(ajax): fetchJSON to attempt parse JSON when missing content-type header
Co-authored-by: Nikhil Hundare <nikhil.hundare@gmail.com>
This commit is contained in:
parent
943618fdcb
commit
63bb012e36
3 changed files with 26 additions and 1 deletions
5
.changeset/eight-cooks-clap.md
Normal file
5
.changeset/eight-cooks-clap.md
Normal file
|
|
@ -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.
|
||||||
|
|
@ -193,7 +193,10 @@ export class Ajax {
|
||||||
|
|
||||||
/** @type {any} */
|
/** @type {any} */
|
||||||
let body = responseText;
|
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 {
|
try {
|
||||||
body = JSON.parse(responseText);
|
body = JSON.parse(responseText);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|
|
||||||
|
|
@ -166,6 +166,23 @@ describe('Ajax', () => {
|
||||||
expect(response.body).to.eql('!@#$');
|
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', () => {
|
describe('given a request body', () => {
|
||||||
it('encodes the request body as json', async () => {
|
it('encodes the request body as json', async () => {
|
||||||
await ajax.fetchJson('/foo', { method: 'POST', body: { a: 1, b: 2 } });
|
await ajax.fetchJson('/foo', { method: 'POST', body: { a: 1, b: 2 } });
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue