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
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.
then(resp => resp.json())
by then(resp => resp.text()).then(console.log)
to see what the served content looks likenetwork
tabmyURL/test
response
: that will be the text content. It shoud be properly formatted JSON.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With