Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
36
rated 0 times [  41] [ 5]  / answers: 1 / hits: 15997  / 8 Years ago, tue, may 17, 2016, 12:00:00

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


More From » node.js

 Answers
35

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.


[#62130] Monday, May 16, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
pranav

Total Points: 693
Total Questions: 119
Total Answers: 119

Location: Greenland
Member since Fri, Jul 31, 2020
4 Years ago
pranav questions
Thu, Feb 10, 22, 00:00, 2 Years ago
Tue, Dec 28, 21, 00:00, 2 Years ago
Mon, Sep 6, 21, 00:00, 3 Years ago
Mon, Mar 8, 21, 00:00, 3 Years ago
;