Axios interceptor intercepting all Axios requests

Viewed 950

I have used an Axios interceptor to intercept my Axios request for login. But it is also being used by other axios requests. Does having an interceptor means it will be used by all axios requests? If yes, how do I only use it for a particular request. In this case, my login request?

  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);

This is the other axios request:

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

But the Axios intercpetor of the login Axios request is also called for the above request.

1 Answers

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

Yes

how do I only use it for a particular request?

I would recommend creating separate Axios instances for each usage.

For example

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

You could also use the default axios instance for your non-authenticated requests.

Related