React Router + Axios 拦截器。如何进行重定向?

2024-04-05

我有一个 axios 拦截器,当用户被强制注销(由于令牌过期)时,我想返回我的主页。

我不确定如何将反应路由器传递给它。我正在使用 mobx,但不确定这是否能帮助我解决这个问题。

export const axiosInstance = axios.create({
    baseURL: 'https://localhost:44391/api',
    timeout: 5000,
    contentType: "application/json",
    Authorization: getAuthToken()
  })

  axiosInstance.interceptors.response.use(function (response) {
    return response;
  }, function (error) {
    const originalRequest = error.config;
    if(error.code != "ECONNABORTED" && error.response.status === 401 && !originalRequest._retry){
      originalRequest._retry = true;
      return axiosInstance.post("/tokens/auth",{
        "refreshToken": getRefreshToken(),
        "grantType": "refresh_token"
    }).then(response => {
        localStorage.authentication = JSON.stringify(response.data);
        updateAuthInstant();
        return axiosInstance(originalRequest)
      });

    }
   return Promise.reject(error);
  });

您应该添加history https://www.npmjs.com/package/historynpm 包。通过此功能,您可以创建浏览器历史记录并在应用程序的其他位置使用它。

例如:

// routing.js

import createHistory from 'history/createBrowserHistory';

export const history = createHistory();

在包含您的路线的组件中。

import { Route, Router } from 'react-router-dom';
import { history } from './routing.js';

import ComponentA from './ComponentA';
import ComponentB from './ComponentB';

const Routes = () => (
  <Router history={history}>
    <div>
      <Route exact path='/route1' component={ComponentA} />
      <Route exact path='/route2' component={ComponentB} />
    </div>
  </Router>
);

在您想要控制路由的其他文件中:

import { history } from './routing.js';

function changeRoute() {
  // things happening here..
  history.push('/route2');
} 

打电话时changeRoute()路径更新为/route2 and ComponentB将被渲染。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

React Router + Axios 拦截器。如何进行重定向? 的相关文章

随机推荐