PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 13, 2022

[FIXED] How to configure axios interceptor globally with express?

 October 13, 2022     axios, interceptor, typescript     No comments   

Issue

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?


Solution

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


Answered By - Phil
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing