How to redirect from axios interceptor with react Router V4?

后端 未结 8 2336
忘了有多久
忘了有多久 2021-01-30 17:36

I want to make a redirection in axios interceptors when receiving a 403 error. But how can I access the history outside React components ?

In Navigating Programatically

8条回答
  •  感动是毒
    2021-01-30 18:24

    I solved this task by creating browser history from history (https://github.com/ReactTraining/history) package and passing it into the interceptor function and then calling .push() method from it.

    The main file code (part of it):

    // app.js
    import { createBrowserHistory } from 'history';
    import httpService from './api_client/interceptors';
    
    ...
    
    const history = createBrowserHistory();
    httpService.setupInterceptors(store, history);
    

    Interceptor configuration:

    import axios from 'axios';
    
    export default {
      setupInterceptors: (store, history) => {
    
          axios.interceptors.response.use(response => {
            return response;
          }, error => {
    
          if (error.response.status === 401) {
            store.dispatch(logoutUser());
          }
    
          if (error.response.status === 404) {
             history.push('/not-found');
          }
    
          return Promise.reject(error);
        });
      },
    };
    

    Also, you should use Router from react-router (https://github.com/ReactTraining/react-router) and pass the same history object as history param.

    // app.js
    ...
    ReactDOM.render(
      
         
            ...
         
      
    , document.getElementById('#root'))
    

提交回复
热议问题