Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: SyntaxError: Unexpected end of JSON input at fetch.then.response

I get this error every time I try to use the POST method in my API.

SyntaxError: Unexpected end of JSON input at fetch.then.response 

When I use the GET method I get the data normally. This is the code:

const teste = () => {
fetch("myURL/test", {
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify({
        id: 1,
        name: "Teste",
        amount: 1,
        value: 3
    })
})
.then(response => response.json()) //Here is the error
.then(data => {
    console.log(data);
})
.catch((err)=>console.log(err))}

Can someone help me? Thank you.

EDIT: I just add this line to see the log:

.then(response => console.log(response))

Here is what I got:

Response {
type: "cors",
url: "myURL/test",
redirected: false,
status: 201,
ok: true,
…}
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 201
statusText: ""
type: "cors"
: "myURL/test"
__proto__: Response
like image 405
Ricardo Sanches Avatar asked Mar 03 '19 18:03

Ricardo Sanches


1 Answers

It means that the page fetched at myURL/test does not responds with JSON content, or with malformed JSON content. This is not an error in your script, which is fine, this is an error with your server, that is not serving JSON content at myURL/test.

Also, note that servers might not respond similarly to GET requests and POST request for the same URL! If you fetch valid JSON from a GET request but, as you described, failed to fetch valid JSON from a POST request, your server might be serving different content depending on the request type. Investigate that.

Debug tips

  • Replace then(resp => resp.json()) by then(resp => resp.text()).then(console.log) to see what the served content looks like
  • Use Postman to simulate API calls, and see what the served content looks like, with more details
  • Examine the response with the developer tools:
    1. In Chrome
    2. Open the console (F12)
    3. Go to the network tab
    4. Click on the file server by myURL/test
    5. Click on response: that will be the text content. It shoud be properly formatted JSON.
like image 135
Nino Filiu Avatar answered Sep 19 '22 20:09

Nino Filiu