Categories
JavaScript Answers

How to use Axios Interceptors retry original request and access original promise with JavaScript?

Spread the love

Sometimes, we want to use Axios Interceptors retry original request and access original promise with JavaScript.

In this article, we’ll look at how to use Axios Interceptors retry original request and access original promise with JavaScript.

How to use Axios Interceptors retry original request and access original promise with JavaScript?

To use Axios Interceptors retry original request and access original promise with JavaScript, we can retry the original request after we get the refresh token in the error handler function.

For instance, we write

const refreshToken = async (store) => {
  if (store.state.auth.isRefreshing) {
    return store.state.auth.refreshingCall;
  }
  store.commit("auth/setRefreshingState", true);
  const {
    data: { token },
  } = await Axios.get("get token");
  store.commit("auth/setToken", token);
  store.commit("auth/setRefreshingState", false);
  store.commit("auth/setRefreshingCall", undefined);
  store.commit("auth/setRefreshingCall", refreshingCall);
  return Promise.resolve(true);
};

Axios.interceptors.response.use(
  (response) => response,
  async (error) => {
    const status = error.response ? error.response.status : null;

    if (status === 401) {
      await refreshToken(store);
      error.config.headers["Authorization"] =
        "Bearer " + store.state.auth.token;
      error.config.baseURL = undefined;
      await Axios.request(error.config);
    }

    return Promise.reject(error);
  }
);

to define the refreshToken function.

It it, we make a get request with Axios.get to get the refresh token from token.

Then in the error handler that we call Axios.interceptors.response.use with, we check if the response status is 401.

If it is, then we call refreshToken to get the refresh token.

And then we set the token as the value of error.config.headers["Authorization"].

Then we call Axios.request to make the request with the error.config.

We then call Promise.reject to reject the promise.

Conclusion

To use Axios Interceptors retry original request and access original promise with JavaScript, we can retry the original request after we get the refresh token in the error handler function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *