Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whatwg Fetch fails when json parsing an empty response, how can I prevent it?

Tags:

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.

response.json() will return a promise so I don't know beforehand what the body of the response is, and when the body is empty the JSON parsing will fail with the error:

SyntaxError: Unexpected end of input

So my question is, how to prevent parsing the response when its empty?

Thanks

like image 223
Beldar Avatar asked May 17 '16 15:05

Beldar


People also ask

What is response json () in fetch?

json() The json() method of the Response interface takes a Response stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON .

How do I get json from fetch response?

To get JSON from the server using the Fetch API, you can use the response. json() method. The response. json() method reads the data returned by the server and returns a promise that resolves with a JSON object.

Does fetch return a json?

The simplest use of fetch() takes one argument — the path to the resource you want to fetch — and does not directly return the JSON response body but instead returns a promise that resolves with a Response object.


1 Answers

Once you have the Response object, inspect the headers and see what Content-Length says. Based on that you can know whether or not there is something to parse. But also, it seems bogus for the server to return an application/json resource that is empty, as that is not JSON.

like image 81
Anne Avatar answered Oct 14 '22 06:10

Anne