2

I'm curious about the difference between axios interceptor and default header.

I want to add authorization in header.

I know I can manage authorization header with axios interceptor and default header. (Attach Authorization header for all axios requests)

I'm not sure when to use the interceptor and default header respectively.

Is it simply that axios provides two methods?

Dev_Kim
  • 43
  • 8

1 Answers1

5

Default headers are assigned statically. The values you place into them must be known at the time your code executes.

axiosOrInstance.defaults.headers.common["x-value"] = "some value you must know";

Interceptors are functions that execute per request / response. This means they can access values that might not have been available earlier or even values specific to the current request.

axiosOrInstance.interceptors.request.use(config => ({
  ...config,
  headers: {
    ...config.headers,
    "x-value": "whatever"
  }
}), null, {
  synchronous: true,
  runWhen: config => config.url === "only/run/for/this/url"
})

They can also be asynchronous and make other async calls before resolving

axiosOrInstance.interceptors.request.use(async config => {
  const someValue = await getSomeAsyncValue()
  return {
    ...config,
    headers: {
      ...config.headers,
      "x-value": someValue
    }
  };
});
Phil
  • 157,677
  • 23
  • 242
  • 245
  • Thank you for your answer. Sorry for the many questions. Assuming that the token is put in Authorization. After receiving the token from the api, putting it in defaults and putting it in the axios Interceptor are the same as a result, right? – Dev_Kim Mar 14 '22 at 08:21
  • @Dev_Kim correct. The header defaults will apply to any request you make after that – Phil Mar 14 '22 at 08:42