Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
}
like image 678
Ben Avatar asked Apr 23 '18 06:04

Ben


1 Answers

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.

like image 195
Niladri Avatar answered Nov 07 '22 22:11

Niladri