Whatwg fetch does not work when json parses an empty answer, how can I prevent it?

I use the Fetch API both in the interface and in the backend (NodeJS), a problem that I had to encounter occurs when parsing the response as json.

response.json() will return a promise, so I don’t know in advance what the response body is, and when the body is empty, the JSON parsing will fail:

SyntaxError: Unexpected end of input

So my question is: how to prevent parsing the answer when it is empty?

thanks

+7
json javascript fetch
source share
3 answers

Once you have a Response object, check the headers and see what Content-Length says. Based on this, you can find out if there is something that needs to be analyzed. But it also seems to be a fake for the server to return the application/json resource, which is empty as it is not JSON.

+6
source share

Since response.json() returns 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); }); 

Update

As mentioned below, if you try to read response twice, you get an error message: TypeError: Already Read .

As a workaround, you can clone original answer 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); }); 
+4
source share

Why don't you handle the error when trying to catch

 try { body = JSON.parse(body) } catch (err) { } 
0
source share

All Articles