0

I am trying to understand this code. And also how to use it

https://stackoverflow.com/a/53294310/2897115

createAxiosResponseInterceptor() {
    const interceptor = axios.interceptors.response.use(
        response => response,
        error => {
            // Reject promise if usual error
            if (errorResponse.status !== 401) {
                return Promise.reject(error);
            }

            /* 
             * When response code is 401, try to refresh the token.
             * Eject the interceptor so it doesn't loop in case
             * token refresh causes the 401 response
             */
            axios.interceptors.response.eject(interceptor);   <---- What does this do

            return axios.post('/api/refresh_token', {
                'refresh_token': this._getToken('refresh_token')
            }).then(response => {
                saveToken();
                error.response.config.headers['Authorization'] = 'Bearer ' + response.data.access_token;
                return axios(error.response.config);  <--- what does this do
            }).catch(error => {
                destroyToken();
                this.router.push('/login');
                return Promise.reject(error);
            }).finally(createAxiosResponseInterceptor);
        }
    );
}

Generally i use axios script with access_token is as:

const url = "dj-rest-auth/password/change/";
  const auth = {
    headers: {
      Authorization: "Bearer " + localStorage.getItem("access_token"),
      Accept: "application/json",
      "Content-Type": "application/json",
    },
  };
  const data = {
    old_password: old_password,
    new_password1: new_password1,
    new_password2: new_password2,
  };
  const promise = axios.post(url, data, auth);
  promise
    .then((res) => {
         console.log(res)
      })
    .catch((err) => {
        if (err.response) {
          console.log(`${err.response.status} :: ${err.response.statusText}`)
          console.log(err.response.data)
        }
      })

And in this code how to use the interceptor

Santhosh
  • 9,965
  • 20
  • 103
  • 243

1 Answers1

0

Eject interceptor

axios.interceptors.response.eject(interceptor); <---- What does this do

Internally, interceptors.response is an array of interceptors, the method axios.interceptors.response.use return the id of the new interceptor. Calling eject passing the id of the interceptor will set the corresponding item in the array to null, and the interceptor has no effect anymore.

When we receive the response code 401, we use the interceptor to send another request to get the token. To avoid the infinity loop if the latter also receives the response code 401, we eject the interceptor in this case.

Resend original request

return axios(error.response.config); <--- what does this do

After receiving the token, we want to resend the original request, its configuration is stored in error.response.config according to the response schema

To use the function, call it before sending the request. (People talk about it in the thread of the accepted answer.)

Đăng Khoa Đinh
  • 5,038
  • 3
  • 15
  • 33