[英]Store token generated on fetch() with React.js
从此代码中,我得到一个令牌,我需要存储该令牌以用于另一次访存,以便刷新令牌,这是最好的方法?
我只能在函数内访问变量.then
...
我宁愿将令牌存储在编码的cookie中,但是我不怎么处理cookie的反应,也不怎么编码或解码它们。
componentDidMount() {
fetch("theURL/api-token-auth/", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
email: "EMAIL",
password: "PASS"
})
})
.then(res => {
if (res.ok) {
return res.json();
} else {
throw Error(res.statusText);
}
})
.then(json => {
this.setState({
isLoaded: true,
token: json
});
let token = this.state.token;
console.log("var token: ", token);
})
.catch(error => console.error(error));
}
看一下localStorage,这是存储令牌的好地方。
localStorage.setItem('token', 'userToken');
然后,要恢复该值,请执行以下操作: const token = localStorage.getItem('token');
在这里深入了解: Web存储
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.