我正在尝试通过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'
)
}
你可以使用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)
)
}