How to redirect from axios interceptor with react Router V4?

后端 未结 8 2110
忘了有多久
忘了有多久 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:38

    The best solution I found is to define axios.interceptors inside my main React components and use that to handle errors : ( And with withRouter from Router V4 )

    import {withRouter} from 'react-router-dom';
    
    class Homepage extends Component {
      static propTypes = {
        history: PropTypes.object.isRequired
      }
    
      constructor(props){
        super(props);
    
        let that = this;
        axios.interceptors.response.use(function (response) {
            // Do something with response data
            return response;
          }, function (error) {
            // Do something with response error
            if(error.response.status === 403) { that.handle403() }
    
            // Trow errr again (may be need for some other catch)
            return Promise.reject(error);
        });
    
      }
    
      handle403(){
        this.props.history.push('/login');
      }
    

提交回复
热议问题