Axios拦截器拦截所有Axios请求

时间:2020-11-03 23:41:07

标签: javascript axios

我使用了Axios拦截器来拦截我的Axios登录请求。但是其他axios请求也正在使用它。拥有拦截器是否意味着所有axios请求都将使用它?如果是,我如何仅将其用于特定请求。在这种情况下,我的登录请求是什么?

  Axios.interceptors.response.use(res => {
          // console.log(`complete response ---> ${JSON.stringify(res)}`)
          // console.log(`This is the login response----> ${JSON.stringify(res.headers)}`)
          const authorization = res.headers.authorization;
          console.log(`Entering login`);
          const bearerToken = authorization.substring(7, authorization.length);
          const userLoginResponse: LoginResponse = {
            httpStatus: res.status,
            token: bearerToken,
            user: {
              .
              .
              .
            }
          }
          this.authParams = {
            .
            .
            .
            .
          }

          //console.log(`This is the userLoginResponse ---->${JSON.stringify(userLoginResponse)}`)
          this.setObject();
          resolve(userLoginResponse)
          return res;
        }, (error) => {
          console.log(`This is the error status ---> ${error.response.status}`)
          if (error.response.status === 401) {
            resolve(error.response);
          }
        })
        await Axios.post(loginAPIURL, params, config);

这是另一个axios请求:

  const submitAPIURL =
          process.env.REACT_APP_API_ADD_INITIATIVE_URL ||
          "";
          axios.post(submitAPIURL, initiative, config).then(submitRes =>{
            resolve(submitRes.headers)
          }).catch(error => {
            reject(error);
          })       
    });

但是,上述请求也会调用登录Axios请求的Axios接口。

1 个答案:

答案 0 :(得分:1)

拥有拦截器是否意味着所有axios请求都将使用它?

如何仅将其用于特定请求?

我建议为每种用法创建单独的Axios实例。

例如

const myAuthenticatedApiClient = axios.create({
  baseURL: process.env.REACT_APP_API_WHATEVER_URL
})

const myOtherApiClient = axios.create({
  baseURL: process.env.REACT_APP_API_ADD_INITIATIVE_URL
})

myAuthenticatedApiClient.interceptors.response.use(res => {
  // whatever
})

myAuthenticatedApiClient.post(...) // will use the interceptor

myOtherApiClient.post("", initiative, config) // no interceptor on this one

您还可以将默认的axios实例用于未经身份验证的请求。