更新时间:2023-09-20 21:46:10
我通常要做的是将令牌保留在本地存储中,这样即使用户离开站点,我也可以保留令牌.
What I usually do is to keep the token in the local storage, this way I can persist the token even if the user leaves the site.
localStorage.setItem('app-token', theTokenFromServer);
每次用户加载页面时,我要做的第一件事就是寻找令牌的存在.
Every time the user loads the page, the first thing I do is to look for the existence of the token.
token = localStorage.getItem('app-token');
如果使用react,我会将令牌保持在全局状态(例如,使用redux):
If using react, I'd keep the token on the global state (using redux for example):
function loadAppToken(token) {
return {
type: 'LOAD_TOKEN',
payload: { token },
};
}
使用香草javascript,可以将其保留在我的连接实用程序中.可能类似于以下内容:
With vanilla javascript I'd keep it on my connection utility. Which might look something like the following:
const token = localStorage.getItem('app-token');
export function request(config) {
const { url, ...others } = config;
return fetch(url, {
...others,
credentials: 'include',
headers: {
'Authorization': `Bearer ${token}`
},
});
}
与以前的代码类似,我仍然在react应用中有一个fetch实用程序,但是我会通过在redux中间件中为每个单个请求获取令牌,从而在选项中发送令牌.
I'd still have a fetch utility in a react app, similar to the previous code, but I'd send the token in the options, by getting it in a redux middleware for every single request.