Home > Blockchain >  SyntaxError: Unexpected end of JSON input in fetch api
SyntaxError: Unexpected end of JSON input in fetch api

Time:09-12

if i do this->

fetch(
      //something,
      options
    )
      .then((response) => response.json() )  

it gives me error 'SyntaxError: Unexpected end of JSON input in fetch api' but if i remove .json() after response like->

fetch(
      //something,
      options
    )
      .then((response) => response )

it stops throwing error. can anyone explain me the issue

CodePudding user response:

response.json() will only work if you receive valid JSON as a response, so you should test first to see if it's valid JSON before calling response.json(). This is how I usually do it.

    async getStuff(stuffId)  {
        try {
            const response = await fetch(`${this.url}/getstuff`, {
                method: 'get',
            });
            
            if (response.status === 200) {
                return await response.json();
            } else {
                return Promise.reject(new Error(`${response.status}`));
            }
        } catch (error) {
            console.log("Error during create minute: ", error);
            throw error;
        }
    }

CodePudding user response:

as @iLittleWizard and @derpirscher said in the comment,

try

fetch(
      //something,
      options
    )
    .then(response=> response.text()).then(t => console.log(t))

in the log you can see the json response. try copy & paste the logs to json validator site(like devutils.org)

you can get hint from the site or you should copy & paste the response here for more help

  • Related