Hi I'm setting default axios headers in request interceptor but these headers are not accessible in another function... in axios axios documentation it is mentioned that global-axios-defaults are global...below is my sample code need help
axios.interceptors.request.use(function (config) { axios.defaults.headers.accesstoken= "some_access_token" axios.defaults.headers.client = "some_client" axios.defaults.headers.uid = "some_uid" return config; },function (error) { return Promise.reject(error); });
On page load componentDidmount executes but axios default headers are undefined in this function
componentDidMount: function() { console.log(axios.defaults.headers) #its giving me undefined axios.get("http://some_url_for_get_request.json", { headers: { accesstoken: axios.defaults.headers.accesstoken, uid: axios.defaults.headers.uid, client: axios.defaults.headers.client } }) }
headers. post['Content-Type'] = 'application/x-www-form-urlencoded'; See the global options here (Request Config)
Instead of adding the headers to each request, you can put them as default headers, and they will apply to all the requests. To do so, use the defaults. headers property of the axios object. This snippet will add the x-rapidapi-key header to all the requests.
When you are using the Axios library and to pass custom headers, you need to construct headers as an object with the key name 'headers'. The 'headers' key should contain an object, here it is Content-Type and Authorization .
You can set the default Custom Headers in Axios for every XHR call like this:
axios.defaults.headers.common = { "X-Requested-With": "XMLHttpRequest", "X-CSRFToken": "example-of-custom-header" };
You can also add configurations onward like this:
window.axios.defaults.headers.post['xsrfCookieName'] = 'CSRFToken'; window.axios.defaults.headers.post['xsrfHeaderName'] = 'X-CSRFToken'; window.axios.defaults.headers.post['responseType'] = 'json'; window.axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
Also, you can create a configuration passed into an instance.
on your MAIN.JS
import axios from "axios"; const base = axios.create({ baseURL: "http://127.0.0.1:8000/", }); Vue.prototype.$http = base; Vue.prototype.$http.interceptors.request.use( config => { let accessToken = localStorage.getItem('token'); if (accessToken) { config.headers = Object.assign({ Authorization: `Bearer ${accessToken}` }, config.headers); } return config; }, error => { return Promise.reject(error); } );
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