Reputation: 18451
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.
Upvotes: 4
Views: 6695
Reputation: 4127
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.
Upvotes: 5