I´m trying to use fetch to load some server data. Here is the code:
fetch('/user', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-type': 'application/json'
},
body: JSON.stringify({
data: 'test'
})
})
.then(response => {
if (response.status !== 200) {
console.log('Fetch status not OK');
}
else {
console.log('Fetch ok');
console.log(response); // Undefined here
}
})
.catch(error => {
console.log('network error');
});
At the browser (network) I can see the response payload being returned from server, but my response contains undefined
. I can imagine this shall be simple, but I can´t find out what is happening here.
I was having a similar issue, where response.body
was returning undefined
. Not strictly the same as the OP's code, but I'm guessing this may have been the same issue, and also searching led me here, so posting my answer.
This happens because the body has not been read yet, only the response headers have arrived. The correct way of accessing the response body is:
fetch('/user').then((resp) => resp.json().then((body) => console.log(body)))
The various ways of reading the body (as text, JSON, etc...) are documented here.
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