亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

axios攔截器攔截所有axios請求

axios攔截器攔截所有axios請求

MMMHUHU 2023-07-06 15:30:29
我使用了 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 回答

?
PIPIONE

TA貢獻1829條經驗 獲得超9個贊

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


查看完整回答
反對 回復 2023-07-06
  • 1 回答
  • 0 關注
  • 177 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號