[英]Store token generated on fetch() with React.js
From this code I get a token, I need to store the token to use in another fetch so I can refresh the token, what's the best way to do it? 从此代码中,我得到一个令牌,我需要存储该令牌以用于另一次访存,以便刷新令牌,这是最好的方法?
I can only access the variable inside the function .then
... 我只能在函数内访问变量
.then
...
I would prefer to store the token in a encoded cookie, but I don't how to handle cookies em react, or how to encode or decode them. 我宁愿将令牌存储在编码的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));
}
Take a look on localStorage, is a good place for store tokens. 看一下localStorage,这是存储令牌的好地方。
localStorage.setItem('token', 'userToken');
And then to recover the value just do: const token = localStorage.getItem('token');
然后,要恢复该值,请执行以下操作:
const token = localStorage.getItem('token');
Take a deeper look here: Web Storage 在这里深入了解: Web存储
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.