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.
i suggest you to do this in an interceptor before request sent like this :
axios.interceptors.request.use(function (config) {
config.headers.common = {...config.headers.common, "X-CSRF-TOKEN": () => store.state.csrf}
return config;
}, function (error) {
// Do something with request error
logger.error(error);
return Promise.reject(error);
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With