从这段代码中我得到了一个 token ,我需要存储 token 以在另一个提取中使用,这样我就可以刷新 token ,最好的方法是什么?
我只能访问函数.then
中的变量...
我更愿意将 token 存储在编码的 cookie 中,但我不知道如何处理 cookie em react,也不知道如何编码或解码它们。
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,它是存储 token 的好地方。
localStorage.setItem('token', 'userToken');
然后要恢复值(value),只需执行以下操作:
const token = localStorage.getItem('token');
在这里深入了解:Web Storage
关于javascript - 使用 React.js 存储在 fetch() 上生成的 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51426672/