-2

I need to fetch JSON data from a localhost server using JS.

The fetch request throws an error:

Uncaught (in promise) SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data

It looks like the answer is empty, but when I open the browser dev tool I can see the JSON data in the network section.

fetch(url, init)
 .then(res => res.json()) //return the error

fetch(url, init)
 .then(res => res.text()) //return an empty string

The result I can see in the network section is well formatted and when I copy/paste it to manually use JSON.parse() I get the right result.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
nem0z
  • 1,060
  • 1
  • 4
  • 17
  • See if there are CORS errors in the console - if not show an example of the JSON and – mplungjan Oct 04 '21 at 10:59
  • I guess there are some hidden warnings in the backends output. Take a look at the raw message you receive and you will find the problem – Thallius Oct 04 '21 at 11:05
  • Most likely your backend does not returning a valid JSON. Sometimes this happens if your url is not correct and backend or proxy returns a default not found html page. Try to inspect the request in developers tools in browser to see what response you are getting. – metodribic Oct 09 '21 at 12:26

1 Answers1

0

You have to return the promise and than wait:

const method = async() =>{
    return fetch(url, init)
     .then(res => res.json())
     .catch(err)=>{
       //manage error here
    }
}

than you do :

method().then(res=>....)

For more info look here : How to get data returned from fetch() promise?

Singh
  • 783
  • 1
  • 6
  • 24