如果令牌过期则注销 [英] Logout if token is expired
问题描述
我正在开发一个包含许多 API 请求的 React 应用程序.应用程序的结构是
I'm working on a react application that consists of many API requests. The structure of the application is
登录时,我在响应时收到一个令牌,并将令牌保存在我的本地存储中以用于其他 API 请求.
When logging in, I'm receiving a token on response and I'm saving the token in my local storage to be used in other API requests.
此令牌每 30 分钟过期一次,如果我在 30 分钟后发出 API 请求,我的请求中会收到 401 状态.我正在使用此 401 状态注销并清除本地存储中的令牌数据.
This token is expired every 30 minutes and if I do an API request after 30 minutes, I'm receiving a status of 401 in my request. I'm using this 401 status to do my logging out and clearing token data in local storage.
示例请求
export function stationDailyUsage(data) {
return dispatch => {
dispatch(dailyUsageLoading());
axios.get(`${API_URL}/Dashboard/DailyUsage?type=${data.type}&date=${data.date}`, {
headers: {
'Authorization': `Bearer ${token}`
},
})
.then(res => {
if (res.data.success === true) {
dispatch(dailyUsageSuccess(res.data));
} else {
console.log("error");
}
})
.catch(function (error) {
if(error.response.status === 401){
dispatch(logout());
}
});
}
}
所以要以这种方式注销,我必须对我使用的每个 API(大约 40 个 API)进行检查.这是最好的方法还是有更好的方法来处理注销.我已经阅读了 axios 拦截器
,但不清楚如何在我的系统中实现它.非常感谢任何帮助.
So to logout this way I have to do this check for every API I use (Around 40 APIs ). Is this the best approach to follow or is there a better way to handle the logout. I've read about axios interceptors
but was not clear about how to implement it in my system. Any help is greatly appreciated.
推荐答案
把这段代码放在你的项目初始化或加载部分,并运行一次那么每次你调用 axios
这段代码都会检查错误
Put this code in your project initialize or loading section, and run it once
then every time you call axios
this code will check errors
在此处更改您的变量并使用它
Change your variable here and use it
// Add a request interceptor
axios.interceptors.request.use((config) => {
let token = localStorage.getItem("token");
if (token) {
config.headers.credentials = 'include';
config.headers.Authorization = `Bearer ${token}`;
config.headers['Access-Control-Allow-Origin'] = '*';
config.headers['Content-Type'] = 'application/json';
}
return config;
}, (error) => {
alert('interceptor request has error');
return Promise.reject(error);
});
// Add a response interceptor
axios.interceptors.response.use((response) => {
return response;
}, (error) => {
if (error.response && error.response.data && error.response.data.error &&
(error.response.data.session === false || error.response.data.session === "false")) {
localStorage.removeItem("userId"); // <-- add your var
window.location = "/"; // <-- add your path
}
else if (error.response && error.response.data && error.response.data.error && error.response.data.error.message) {
toastMessage(error.response.data.error.message, 1);
}
else
if (error.response && error.response.status === 401) {
localStorage.removeItem("userId"); // <-- add your var
window.location = "/"; // <-- add your path
} else
return Promise.reject(error);
});
这篇关于如果令牌过期则注销的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!