Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript fetch response returning undefined

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.

like image 406
Mendes Avatar asked Sep 19 '25 19:09

Mendes


1 Answers

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.

like image 195
Xavier Shay Avatar answered Sep 21 '25 10:09

Xavier Shay