In axios, from global response interceptor, Is that possible to call the then()

Viewed 791

I'm trying to handle jwt token expiration (401) in a global interceptor. Once I get a new token, I'd like to retry the failed method and call it's then(). Is that possible to do that?

Here is my interceptor.

ea_axios.interceptors.response.use(undefined, function (error) {
if (error.response){
    let res = error.response;
    if (res.status === 401 && res.config && !res.config.__isRetryRequest) {        
        ea_axios.get('/refresh').then(function(response){
            Object.assign(eops_axios.defaults, {headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + sessionStorage.accessToken
            }});
            error.config.__isRetryRequest = true
            error.config.headers.Authorization = 'Bearer ' + response.data
            return axios(error.config);
        }).catch(error => alert(error), reject(error));
    } else {
        return Promise.reject(error);
    }
} else {
    return Promise.reject(error);
}

});

I'm using axios for all get/put/post requests. And, Once the above interceptor got the new access token, I need to retry the same axios method and it's then() method. Like wise, I've lot of axios calls which needs the same handling.

ea_axios.get('/options')
  .then(function(response){
    if (response.data != undefined && response.data != ''){
      response.data.forEach( function(option) {
        if (option.optionName == 'applicationCloseDate'){
          _this.setState({ applicationCloseDate: option.optionValue });
        }
      });
      _this.setState({ error: false })
    }

  })
  .catch(error => _this.setState({ error: true }));

Can anyone suggest how to do that with axios?

0 Answers
Related