使用fetch进行反应以获取令牌并检查响应状态?

问题描述 投票:0回答:1

我正在尝试通过REST调用和JWT令牌检查登录状态,这样如果该状态不正确,那么它将返回false,但这就是我得到的。

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
    )
}

我尝试在这个函数中添加一个检查,但后来我不再打印出令牌了

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'
    )
}
javascript reactjs rest fetch
1个回答
0
投票

你可以使用catch块吗?像这样:

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)
    )
}
© www.soinside.com 2019 - 2024. All rights reserved.