axios set default headers dynamically

2019-07-31 04:08发布

问题:

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)