【问题标题】:axios interceptor: need to undestand the javascript codeaxios拦截器:需要懂javascript代码
【发布时间】:2021-10-11 06:56:31
【问题描述】:

我正在尝试理解这段代码。以及如何使用它

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);
        }
    );
}

一般我使用带有access_token的axios脚本如下:

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)
        }
      })

以及在这段代码中如何使用拦截器

【问题讨论】:

    标签: axios


    【解决方案1】:

    弹出拦截器

    axios.interceptors.response.eject(拦截器);

    在内部,interceptors.response 是一个拦截器数组,axios.interceptors.response.use 方法返回新拦截器的 id。调用eject传递拦截器的id,会将数组中的对应项设置为null,拦截器不再起作用。

    当我们收到响应码 401 时,我们使用拦截器发送另一个请求以获取令牌。如果后者也收到响应码 401,为了避免无限循环,我们在这种情况下弹出拦截器。

    重新发送原始请求

    返回 axios(error.response.config);

    收到token后,我们要重新发送原始请求,其配置根据response schema存储在error.response.config

    要使用该函数,请在发送请求之前调用它。 (人们在accepted answer.的线程中谈论它)

    【讨论】:

      猜你喜欢
      • 2020-07-20
      • 2020-09-16
      • 2018-11-27
      • 2022-11-09
      • 2019-06-26
      • 1970-01-01
      • 2023-04-06
      • 2021-05-10
      • 1970-01-01
      相关资源
      最近更新 更多