Error: SyntaxError: Unexpected end of JSON input when using fetch()

17,524

From the error message and HTTP response it's evident that if you are using fetch api and returning HTTP 200 from the server side then you should sent some content like "OK" , otherwise it returns empty string and if you use .json() on top the response it results in error as it is not a valid json. If you are not sending any content send HTTP 204 from the server side (no content).

So for your case you should send some content from the server side.

Share:
17,524
Ben
Author by

Ben

Updated on June 14, 2022

Comments

  • Ben
    Ben almost 2 years

    I am having a play with sending JSON between a Go API server and a React based front end. I am getting the following error:

    Error: SyntaxError: Unexpected end of JSON input

    It is saying this is occuring at line 25 which is

    .then(response => response.json())
    

    This is the related function:

    postData() {
    fetch('stuff/', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        name: 'Bob',
        age: 53,
      })
    })
    .then(response => response.json())
    .catch(error => console.error('Error:', error))
    .then(response => console.log('Success:', response));
    }
    

    After trying some troubleshooting i added the error catching to the function with the "success" and "error" outputs so it would at least stop popping the error page and added some console outputs on the API server to see if the data was being passed.

    Apart from the error occurring, everything seems to be working as expected. The Go API server is receiving the json data and I am able to unmarshal it into a structure and write the data to console just fine so I know the data is being passed. No errors are being thrown on the Go side of the operation.

    I'm having trouble working out what may be causing the error? Looking for some suggestions on how I may further troubleshoot this or resolve the error.

    UPDATE: As Dale Suggested i have put .then(response => console.log(response)) into my code. I replaced the standard .then(response => response.json()) with this code. Below is a screenshot of the console from the chrome dev tools.

    response output

    Also it may be worth noting that the error code does not pop up in this case. Could the error be with the server side go code? Below is the handler for the POST endpoint

    func handlePostTest(w http.ResponseWriter, r *http.Request) {
    body, err := ioutil.ReadAll(r.Body)
    if err != nil {
        fmt.Print(err.Error())
    }
    var aPerson Person
    json.Unmarshal(body, &aPerson)
    fmt.Print(" ", aPerson.Name, " ", aPerson.Age)
    }
    
    • Roy Wang
      Roy Wang about 6 years
      The response is not a valid JSON. Test the response with Postman.
    • Ben
      Ben about 6 years
      I'm not familiar with Postman but will try work it out to do a test.
    • Matan Bobi
      Matan Bobi about 6 years
      Can you show us the JSON object you are receiving?
    • Dale King
      Dale King about 6 years
      try .then(response => console.log(response)) and see what you're getting back
    • Niladri
      Niladri about 6 years
      @Ben what are you returning from the POST request in server side as JSON ? it seems to be null so you are getting the error.Did you check the response at the server side?
    • Ben
      Ben about 6 years
      Have made a change to the code as suggested by @DaleKing and edited the post to include a screenshot of the output. Assuming this was meant to replace the original .then(response => response.json())
    • Ben
      Ben about 6 years
      @Niladri having a look i was thinking similar and it make me think if I should be replying with something from the server side. At this stage there is no response that I have coded. In the examples I have found online for handling POST requests I did not notice anything indicating a reply of any kind which is possibly why I missed this. Should it just be responding with an OK code of some sort?
    • Niladri
      Niladri about 6 years
      @Ben if you are using fetch api and returning HTTP 200 from the server side then you should sent some content like ok , otherwise it it returns empty string and if you use .json() in it it results in error as it is not a valid json. If you are not sending any content send HTTP 204 from the server side (no content)
    • Drag13
      Drag13 about 6 years
      You returns readable stream from server. May be this is the answer?
    • Ben
      Ben about 6 years
      @Niladri thanks that did the trick. Just sent back a reply with "OK" as suggested since I don't really have anything worthwhile sending in this situation. Its odd that none of the go tutorials I was reading mentioned this at all. However they may not have been using fetch.
    • Niladri
      Niladri about 6 years
      @Ben nice .. should I post this as the answer?
    • Ben
      Ben about 6 years
      @Niladri yes, please do. It has resolved the error and your explanation was very helpful in helping me understand what was causing the error. thanks again.
    • Dale King
      Dale King about 6 years
      glad you got it sorted
    • Ben
      Ben about 6 years
      @Niladri i have edited my post and got it unlocked so you should now be able to post the answer.
    • Niladri
      Niladri about 6 years
      @Ben ok will do :)
  • William
    William about 3 years
    how to send some contents from the server?
  • Niladri
    Niladri about 3 years
    @AymenKareem it depends on the server side language you are using. Ideally it can any valid json encoded value
  • William
    William about 3 years
    I've this return: return CreatedAtAction("GetBooking", new { id = booking.BookingID }, booking);
  • William
    William about 3 years
    I feel like it returns the newly created object. I'm getting the same error as the title in this thread. Any idea why?