React Router + Axios interceptors. How to Do a red

2019-08-20 21:02发布

问题:

I have an axios interceptors and when a user gets forced logged out(because of expired token) I want to go back to my home page.

I am not sure how to pass react router to it though. I am using mobx but not sure if that will help me with this problem.

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);
  });

回答1:

You should add the history npm package. With this you can create the browser history and use this within other places of your application.

For example:

// routing.js

import createHistory from 'history/createBrowserHistory';

export const history = createHistory();

In your component that contains your routes.

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>
);

And in your other file in which you want to control the routing:

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

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

When calling changeRoute() the path is updated to /route2 and ComponentB will be rendered.