4

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.

6
  • /api? What is your endpoint? Where in the api folder are you trying to access? Commented Nov 9, 2017 at 23:51
  • There are also no brackets on that else statement Commented Nov 9, 2017 at 23:53
  • @4castle, sure. Corrected. Commented Nov 9, 2017 at 23:54
  • 2
    Response cannot be undefined, you'd get a type error when you tried to check the status property at the start of the conditional. You'd never make it to the else branch. Commented Nov 10, 2017 at 0:02
  • 3
    // Undefined here - no it isn't - but you haven't accessed the actual response body yet ... i.e. response.json() would seem to be appropriate for your code - be aware that your .then results in undefined as you aren't returning anything from it - so, later in the promise chain is where you'll be getting undefined (this isn't ALL your code, right) Commented Nov 10, 2017 at 0:04

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.