簡體   English   中英

axios攔截器攔截所有axios請求

[英]Axios interceptor intercepting all Axios requests

我使用了一個 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攔截器。

擁有攔截器是否意味着所有 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實例用於未經身份驗證的請求。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM