5

I was just reading a css-tricks article on how to make you're API request DRY using axios HERE. Now reacting something like this would work fine :

export default axios.create({
  baseURL: 'https://mysite/v3',
  headers: {
    'content-type': 'application/json'
  }
})

The thing is what if i want to pass additional parameters to this instance ? I.E. i have another parameter that i would like to the header like so:

'X-USER-ACCESS-TOKEN': sessionToken,

Also what if i have multiple other options to pass to the header ?

Alexander Solonik
  • 9,838
  • 18
  • 76
  • 174
  • Does this answer your question? [How to set header and options in axios?](https://stackoverflow.com/questions/45578844/how-to-set-header-and-options-in-axios) –  Jun 22 '20 at 11:30
  • @Dan not extactly , i need to pass the `X-USER-ACCESS-TOKEN': sessionToken,` dynamically – Alexander Solonik Jun 22 '20 at 11:38

2 Answers2

6

To pass headers dynamically, you could export a function that takes options as an argument and returns a new instance of axios:

// utils/custom-axios.js

export default function(options = {}) {
  const { 
    headers = {} 
  } = options;
  
  return axios.create({
    baseURL: "https://mysite/v3",
    headers: {
      "Content-Type": "application/json",
      ...headers
    }
  });
}

Then you could use it the following way:

const axios = require("./utils/custom-axios");

const options = { 
  headers: { "X-USER-ACCESS-TOKEN": "secret" } 
};

axios(options)
  .post("./user.json", formData)
  .then(...)
  .catch(...);

// alternatively, don't pass any options 
axios()
  .post("./user.json", formData)
  .then(...)
  .catch(...);
goto
  • 4,336
  • 15
  • 20
0

If I'm getting it right you want to pass headers for distinct calls instead of having them set for all requests using the base configuration?

What about axios.get('url', { headers: 'X-USER-ACCESS-TOKEN': sessionToken }) ?

Benjamin Eckardt
  • 709
  • 6
  • 10