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

问题描述 投票:0回答:2

我有一个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);
  });
reactjs react-router axios react-router-v4 mobx
2个回答
2
投票

您应该添加history npm软件包。这样,您可以创建浏览器历史记录,并在应用程序的其他位置使用它。

例如:

// 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,并且将渲染ComponentB


0
投票
window.location.href = '/user/login'
© www.soinside.com 2019 - 2024. All rights reserved.