[Vuejs]-How to receive re-requested data when data requested by mounted() is re-requested by aixos interceptor

0👍

Seems like you need to return the second request (await for result and return). Right now the result of second request seems to be ignored

axios.interceptors.response.use(
  function (response) {
    return response;
  },
  async function (error) {
    const originalRequest = error.config;
    if (error.response.status === 401 && !originalRequest._retry) {
      error.response.config._retry = true;
      sessionStorage.removeItem("access-token");
      let headers = {
        grant_type: "refresh_token",
        Authorization: sessionStorage.getItem("refresh-token"),
      };
      const [secondError, res] = await axios // await here
        .post("/api/v1/users/refresh_token", {}, { headers: headers })
        .then(async (response) => {
          let token = response.data.data;
          sessionStorage.setItem("access-token", token);
          originalRequest.headers["Authorization"] = token;
          originalRequest.headers["grant_type"] = "grant_type";
          return [null, await axios.request(originalRequest)];
        })
        .catch((err) => {
          console.log(err);
          alert("blablabla.");
          return [err, null];
        });
        // Handle here
        if(secondError) {
          return Promise.reject(secondError);
        }
        return Promise.resolve(res)
    }
    return Promise.reject(error);
  }
);

0👍

The above solution worked for me perfectly. here’s the modified code that I used for my requirement.

export default function axiosInterceptor() {


    //Add a response interceptor
    axios.interceptors.response.use(
        (res) => {
            // Add configurations here
            return res;
        },
        async function (error) {
            const originalRequest = error.config;
            let secondError, res
            if (error.response.status === 401 && !originalRequest._retry) {
                originalRequest._retry = true;

                [secondError, res] = await axios({
                    method: "POST",
                    url: `${baseURL}/account/token/refreshtoken`,
                    withCredentials: true,
                    headers: { "Content-Type": "application/json" },
                })
                    .then(async (response) => {
                        //handle success
                        return [null, await axios.request(originalRequest)];
                    }).catch(function (error) {
                        console.error(error)
                    });
            }
            if (secondError) {
                return Promise.reject(secondError);
            }
            return Promise.resolve(res)
        }
    );
}

Leave a comment