Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

axios set default headers dynamically

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.

like image 716
Chris Avatar asked Oct 27 '25 14:10

Chris


2 Answers

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);
  });
like image 101
Vahid Mehrabi Avatar answered Oct 29 '25 03:10

Vahid Mehrabi


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.

like image 40
str Avatar answered Oct 29 '25 04:10

str