React Router + Axios interceptors. How to Do a redirect?

∥☆過路亽.° 提交于 2019-12-11 17:47:47

问题


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.



来源:https://stackoverflow.com/questions/51388553/react-router-axios-interceptors-how-to-do-a-redirect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!