Javascript 异步和本地存储无法正常工作
所以我使用React和React路由器 我有一个onEnter钩子,它检查用户是否正在验证是/否,并执行所需的操作Javascript 异步和本地存储无法正常工作,javascript,reactjs,promise,react-router,Javascript,Reactjs,Promise,React Router,所以我使用React和React路由器 我有一个onEnter钩子,它检查用户是否正在验证是/否,并执行所需的操作 export function requireAuth(nextState, replaceState) { if (!isAuthenticated()) { if (!Storage.get('token')) replaceState(null, '/login'); return delegate().then(() => replaceStat
export function requireAuth(nextState, replaceState) {
if (!isAuthenticated()) {
if (!Storage.get('token')) replaceState(null, '/login');
return delegate().then(() => replaceState(null, nextState.location.pathname));
}
if (nextState.location.pathname !== nextState.location.pathname) {
return replaceState(null, nextState.location.pathname);
}
}
当令牌过期时,我调用一个委托
函数,该函数如下所示:
export function delegate() {
const refreshToken = Storage.getJSON('token', 'refresh_token');
return getData(endpoint)
.then(res => {
Storage.set('token', JSON.stringify({
access_token: res.data.access_token,
refresh_token: refreshToken,
}));
});
}
委托函数确实会刷新本地存储中的令牌。但是replaceState之后的请求使用的不是更新的令牌,而是上一个令牌。我认为这是一个异步问题,有人更了解这一点吗
编辑:我使用令牌的函数:
function callApi(method, endpoint, data) {
return new Promise((resolve, reject) => {
let headers = {
'Accept': 'application/json',
'X-API-Token': Storage.getJSON('token', 'access_token'),
};
const body = stringifyIfNeeded(data);
const options = { method, headers, body };
return fetch(endpoint, options)
.then(response =>
response.json().then(json => ({ json, response }))
).then(({ json, response }) => {
if (!response.ok) {
reject({ json, response });
}
resolve(json);
}).catch((error, response) => {
reject({ error, response });
});
});
}
您可以分享您在发出请求时使用令牌的位置吗?@chapinkapa我添加了用于发出请求的函数。检查标题;)。
Storage
是异步的吗?顺便说一句,您使用的fetchapi很奇怪。避免这种情况。这应该是返回fetch(端点,选项)。然后(response=>response.ok?response.json():response.json。然后(error=>{throw{error,response};}))
@Bergi Storage只是一个简单的实现,在这里我使用localStorage。