Repository navigation
What is the difference between headers set in axiosInstance.default.headers and in axiosInstance.default.headers.common? #6601
Replies: 1 comment
|
The difference is where in the merge pipeline each one lives. When axios makes a request, it merges headers in this order (each step can override the previous):
When you do In practice: use const instance = axios.create({ baseURL: 'https://api.example.com' })
// these two are equivalent for "send on all methods":
instance.defaults.headers.common['Authorization'] = `Bearer ${token}`
// vs
instance.defaults.headers['Authorization'] = `Bearer ${token}`
// method-specific:
instance.defaults.headers.post['Content-Type'] = 'application/json'The |
Uh oh!
There was an error while loading. Please reload this page.
While setting an Accept header for an AxiosInstance, I noticed that when the headers are passed initially via
const instance = axios.create({headers: {Accept: 'application/json'}}), the header will be set underinstance.defaults.headers.Accept.But wherever I read about overwriting default headers of axios it always mentions overwriting the header under
instance.defaults.headers.common(see also https://www.npmjs.com/package/axios#custom-instance-defaults). Moreover, whether I callaxios.create({headers: {Accept: 'application/json'}})oraxios.create(), the value ofinstance.defaults.headers.common.Acceptwill be 'application/json, text/plain, /', so the headers passed during create do not influence what's under common. I can only manually overwrite it withinstance.defaults.headers.common = {Accept: 'application/json'}So which one takes precedence?
instance.defaults.headers.Acceptorinstance.defaults.headers.common.Accept? I know that if I set it for example directly forinstance.defaults.headers.post.Accept, then this one will take precedence because it is more specific.Or is this a bug in axios 1.7.7 and
instance.defaults.headers.Acceptshould not even be possible?All reactions