0

I'm trying to check the status of a login via REST call and JWT token so that if that status is not ok then it'll return false, but this is what I'm getting.

export function login(data){
    fetch('http://localhost:8000/token-auth/', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(data)
    }).then(res => res.json())
    .then(json => 
         console.log(json.token)  <= This prints correctly
    )
}

I tried adding in a check in this function, but then I no longer get the the token printed out

export function login(data){
    fetch('http://localhost:8000/token-auth/', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(data)
    }).then(res => {
         if(res.ok){
             console.log(res.json()) <= This prints something about promise
             console.log(res.json().token) <= this prints 'undefined'
         } 
    }).then(json => 
         console.log(json.token)  <= This prints 'undefined'
    )
}
Gooby
  • 621
  • 2
  • 11
  • 32
  • You need to return `res.json()` from the first `then`. – 31piy Aug 31 '18 at 09:57
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – 31piy Aug 31 '18 at 09:58

1 Answers1

0

Can you use a catch block instead? Like so:

export function login(data){
    fetch('http://localhost:8000/token-auth/', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(data)
    }).then(res => res.json())
    .then(json => 
         console.log(json.token)
    ).catch(error =>
         console.log(error.response)
    )
}
Brian K.
  • 416
  • 1
  • 6
  • 15