问题
I want to set a header that sent with each request:
axios.defaults.headers.common = {
Accept: 'application/json',
'X-CSRF-TOKEN': store.state.csrf
};
This is only evaluated at the page load. I would like it to be dynamic since the csrf value may change later on. Something like:
axios.defaults.headers.common = {
Accept: 'application/json',
'X-CSRF-TOKEN': () => store.state.csrf
};
However this does not work.
回答1:
You can overwrite/extend the defaults at any time:
// set defaults...
// do requests...
// overwrite CSRF token
axios.defaults.headers.common['X-CSRF-TOKEN'] = store.state.csrf;
// do more requests...
Or you can change the defaults only for a certain instance.
回答2:
You can pass dynamic header as argument after request data.
let config = {
'X-CSRF-TOKEN': store.state.csrf
}
axios.post(url, requestData, config)
来源:https://stackoverflow.com/questions/47020246/axios-set-default-headers-dynamically