在ReactJS项目中,我设置了一个全局Axios拦截器来处理401错误并重定向到登录页面。如果服务器返回401错误,这将按预期工作。
//global interceptor for handling 401 (invalid token) response.
axios.interceptors.response.use(
function (response) {
console.log("Axios defaut interceptor");
return response;
},
function (error) {
if (401 === error.response.status) {
alert(
"Your session has expired. You will be redirected to the login page."
);
window.location = "/login";
} else {
return Promise.reject(error);
}
}
);问题是主页Class组件的构造函数()方法发送了多个GET请求。这会导致警报消息显示多次。
处理该错误并仅重定向到登录页面一次的最佳方法是什么?
发布于 2020-04-18 03:42:27
解决方案是在加载页面之前验证令牌是否存在。
我正在使用Router加载主页:
<Router basename={"/home"}>
<Switch>
<AuthenticateRoute
path="/"
exact={true}
component={<Main component - change this>}
/></Router>在AuthenticateRoute组件中,验证是否存在具有有效到期日期的令牌。
class AuthenticatedRoute extends Component {
render() {
var isValidToken = false;
const token = localStorage.getItem(USER_TOKEN);
if (token === null) isValidToken = false;
var decodedToken = jwt.decode(token, { complete: true });
if (decodedToken.payload === null) isValidToken = false;
//Get the current time in seconds.
var dateNow = new Date();
var nowDateSeconds = parseInt(dateNow.getTime() / 1000);
//Check if token expiry time greater than current time (valid token)
if (decodedToken.payload.exp > nowDateSeconds) {
isValidToken = true;
}
if (isValidToken ) {
return <Route {...this.props} />
} else {
return <Redirect to="/login" />
}
}
}如果令牌无效,将不会加载主页。注意:此代码不会授权/验证令牌。它只是在加载主组件之前检查是否存在有效的带日期的令牌。
有关浏览器中JWT令牌验证的更多详细信息,请单击此处- React - How to check if JWT is valid before sending a post request?
https://stackoverflow.com/questions/61263461
复制相似问题