Home > Back-end >  How to configure axios interceptor globally with express?
How to configure axios interceptor globally with express?

Time:08-18

I want to set up axios interceptor globally for all the http call from axios. Our http call is wrapped in a typescript class Foo:

import Axios, axios from 'axios';
import { configAxios } from 'config';
class Foo {
   Foo() {
      configureAxios();
  }
   public callAxios() {
      axios.request() // send the http request
   }
}
default export new Foo();

In config.ts it defines the interceptor config:

export default function configAxios() {
     Axios.interceptors.request.use(req => { // config request });
     Axios.interceptors.response.use(res => { // config response });
}

But no request or response is intercepted. What am I missing?

CodePudding user response:

First, don't configure interceptors in a class constructor. That will add duplicates every time you create an instance of that class.

I would recommend creating a specific Axios instance to use that has the interceptors bound to it...

// client.ts
import axios from "axios";

const client = axios.create({
  baseURL: "https://example.com" // just an example
});

// Some example interceptors that add properties to the standard request config
// and read it in the response.

interface MyCustomConfig extends AxiosRequestConfig {
  myMagicProperty?: number;
}

api.interceptors.request.use<MyCustomConfig>((config) => ({
  ...config,
  myMagicProperty: performance.now(),
}), null, { synchronous: true });

api.interceptors.response.use((res) => {
  console.log((res.config as MyCustomConfig).myMagicProperty);
  return res;
});

export default client;

This way, you can still access the default instance (or create entirely new ones) without interceptors which can be handy for making authentication or token refresh requests. It also ensures your instance is only created and configured once.

Now simply use this instance in your class

import client from "./client";

class Foo {
  public callAxios() {
    client.request() // send the http request
  }
}

default export new Foo();
  • Related