I\'m using the Fetch API both in the frontend and on the backend (NodeJS), a problem that I\'ve been facing a lot happens when parsing the response as json.
respon
Since response.json() returns a Promise, You can handle the error with catch and return a dummy data object.
fetch('url').then(response => {
return response.json().catch(err => {
console.error(`'${err}' happened, but no big deal!`);
return {};
});
}).then(data => {
console.log(data);
});
As mentioned below, if you try to read response twice, you'll get an error: TypeError: Already Read.
As a workaround, it you can clone the original response and call json on the cloned object.
fetch('url').then(response => {
const responseCopy = response.clone();
return responseCopy.json().catch(_ => response.text());
}).then(data => {
console.log(data);
});