'axios.interceptors.request.use() does not execute the functions body

I'm having problem with axios interceptors. I simplified my code below but it still does not execute the statement inside the "axios.interceptors.request.use()" body. Please see code below and console output for reference. Thank you.

import axios from 'axios'

class AuthenticationService{

    setupAxiosInterceptorsJwt(token){
    
        console.log("Setting up interceptors.")
        
        axios.interceptors.request.use((config) => {
                config.headers.authorization = token
                console.log("Interceptor created.");
            return config;
          }, (error) => {
                console.log("Failed");
            return Promise.reject(error);
          });
      
          console.log("Finished.");
      }

}

export default new AuthenticationService();

Console:

    Setting up interceptors.
    Finished.


Solution 1:[1]

Try returning a value (config) for the "success" handler and rejecting an error for the error handler:

setupAxiosInterceptorsJwt(token) {
  console.log("Setting up interceptors.")

  axios.interceptors.request.use(
    (config) => {
      console.log("Success");
      return config;
    }, (error) => {
      console.log("Failed");
      return Promise.reject(error);
    });

    console.log("Finished.");
  }

That being said, you are specify a "request" interceptor. Technically the handler where you do console.log("Success"); is inaccurate as the request has not yet occurred. Did you intend to instead do a "response" interceptor?

setupAxiosInterceptorsJwt(token) {
  console.log("Setting up interceptors.")

  axios.interceptors.response.use(
    (response) => {
      console.log("Success");
      return response;
    }, (error) => {
      console.log("Failed");
      return Promise.reject(error);
    });

    console.log("Finished.");
  }

Either way, you need to either return the config or return the response and reject an error in the error handler.

Finally, the console.log("Finished."); will probably always log before the other console.log statements due the async nature of the requests.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1