首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Axios拦截器拦截所有Axios请求

Axios拦截器拦截所有Axios请求
EN

Stack Overflow用户
提问于 2020-11-03 23:41:07
回答 1查看 1.1K关注 0票数 2

我使用了一个Axios拦截器来拦截我的Axios登录请求。但是它也被其他axios请求所使用。是否有一个拦截器意味着它将被所有的axios请求所使用?如果是的话,我怎样才能将它用于特定的请求。在这种情况下,我的登录请求?

代码语言:javascript
运行
复制
  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请求:

代码语言:javascript
运行
复制
  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代祷者也被调用为上述请求。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-03 23:58:24

是否有一个拦截器意味着它将被所有axios请求使用?

如何仅用于特定的请求?

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

例如

代码语言:javascript
运行
复制
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实例。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64672337

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档