admin管理员组

文章数量:1300133

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 ?

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 ?

Share asked Jun 22, 2020 at 11:24 Alexander SolonikAlexander Solonik 10.3k19 gold badges85 silver badges185 bronze badges 2
  • Does this answer your question? How to set header and options in axios? – user12641807 Commented Jun 22, 2020 at 11:30
  • @Dan not extactly , i need to pass the X-USER-ACCESS-TOKEN': sessionToken, dynamically – Alexander Solonik Commented Jun 22, 2020 at 11:38
 | 

2 Answers 2

Reset to default 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(...);

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 }) ?

本文标签: javascriptHow to pass dynamic parameters to axios instanceStack Overflow