-4

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

user19562345
  • 1
  • 1
  • 2
  • 1
    What does response look like? Can you show a console.log() of what the fetch returns? – JBrown Sep 11 '22 at 16:28
  • 1
    "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.". That error message indicate that the response is not a valid JSON, and therefore it's unable to parse it into a JavaScript object. Try `console.log()` -ing the response to see what does the request returned – iLittleWizard Sep 11 '22 at 16:31
  • The _Unexpected end of JSON input_ error occurs also when you try to parse an invalid JSON string or an empty array, like `JSON.parse([])` or `JSON.parse("")`. - Your response may be empty. – Christopher Sep 11 '22 at 16:37
  • That means, the response you get is not a valid JSON. It may look like one in the beginning (otherwise you'd get a different error) but at some point it just stops, unexpectedly as the error tells you. Hard to say what the reason is without further details – derpirscher Sep 11 '22 at 16:38
  • Try something like `.then(response=> response.text()).then(t => console.log(t))` to see what the actual response is – derpirscher Sep 11 '22 at 16:40
  • But yeah, of course it stops throwing an error about the invalid JSON, once you remove the JSON parsing... – derpirscher Sep 11 '22 at 16:42
  • https://stackoverflow.com/questions/45696999/fetch-unexpected-end-of-input – vee Sep 11 '22 at 16:44

1 Answers1

-2

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

devapi
  • 1