javascript - axios拦截器拦截所有axios请求

标签 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拦截器。

最佳答案

Does having an interceptor means it will be used by all axios requests?

是的

how do I only use it for a particular request?

我建议为每种用途创建单独的 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 实例。

关于javascript - axios拦截器拦截所有axios请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64672337/

相关文章:

javascript - 浏览器如何缓存在 Flash 中动态加载的图像

向上滚动或向下滚动时的 JavaScript 事件

vue.js - Vuetify 数据表 : Fetch data when expanding a row

javascript - UnhandledPromiseRejectionWarning错误使用axios

laravel - Vue 未使用 unshift 正确更新 ARRAY

javascript - 更改 JavaScript 警报按钮

javascript - Uncaught Error : no data returned for views/AgeTypes.fragment.xml

symfony - axios 中的动态主机

node.js - 使用 Axios 或 fetch 在 Node 内进行 self REST Api 调用?

javascript - 使用小型 Bootstrap 模态的超大背景模态