How to Access History Object Outside of a React Component

后端 未结 3 1181
南方客
南方客 2020-12-15 03:34

First of all, I am pretty familiar with the withRouter HoC, however, in this case, it doesn\'t help because I do not want to access the history object in a comp

3条回答
  •  生来不讨喜
    2020-12-15 04:08

    Today, I faced the same issue. Maybe my solution helps somebody else.

    src/axiosAuthenticated.js

    import axios from 'axios';
    import { createBrowserHistory } from 'history';
    
    
    const UNAUTHORIZED = 401;
    
    axios.interceptors.response.use(
      response => response,
      error => {
        const {status} = error.response;
        if (status === UNAUTHORIZED) {
          createBrowserHistory().push('/');
          window.location.reload();
        }
        return Promise.reject(error);
     }
    );
    
    export default axios;
    

    Also, if you want to intercept any request to add token stored in LocalStorage:

    let user = JSON.parse(localStorage.getItem('user'));
    
    var authToken = "";
    if (user && user.token)
      authToken = 'Bearer ' + user.token;
    
    axios.defaults.headers.common = {'Authorization': `${authToken}`}
    

    To use it, instead of importing from 'axios', import from 'axiosAuthenticated' like this:

    import axios from 'utils/axiosAuthenticated'
    

提交回复
热议问题