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
Reset to default 6To 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
版权声明:本文标题:javascript - How to pass dynamic parameters to axios instance - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741657010a2390818.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论