Home > Software design >  Fetch request error while I can see the good result in the browser dev tool
Fetch request error while I can see the good result in the browser dev tool

Time:10-05

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.

CodePudding user response:

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?

CodePudding user response:

Thx for the help,

the fetch is already used in an async function using await

let data = fetch(url, init)
   .then(res => res.json())
   .catch(e) => { console.log(e) }; //print the same error

There's is no more error in the console, maybe there is a way to show more warning / error ?

The json I try to fetch is :

[
  {"id":"28","search":"\u201cFootball\u201d","value":"16500000"},{"id":"29","search":"\u201cHandball\u201d","value":"9500000"},
]
  • Related