Dav k
Dav k

Reputation: 180

Vue.js2 - How to set a global header from a nested component

I made vue project via Vue cli with a simple-webpack structure. I use Vue resources and vue routes and an API that sends me authorized token when I send the correct credentials for the user.

how can I make the token to sit in the header of all the next requests this user will make.

right now I found a way to save the token to the local storage and send it in the header for each request {headers: {Authorization: localStorage.Authorization}} but I found it not dry and very frustrating.

moreover i'v found the Vue.http.headers.common['Authorization'] = 'token...' - and I want to know how to implement the token from the login request to this global instance.

I've also find this approach - Vue.http.interceptors.push((request, next) => {// setting the header}); but couldn't understand when should I implement this or how to send the data from the component to this object.

Upvotes: 0

Views: 824

Answers (1)

Dav k
Dav k

Reputation: 180

After big research, I've found out that Vue-resource is no longer an official package and instead Axios is.

Vue resource package is still working and will keep being maintained by their creators.

I've migrated to Axios ajax handling package and use the axios configuration and it worked as magic. I've added this line to the main.js file.

axios.defaults.headers.common['Auth'] = localStorage.Auth;

import axios from 'axios' import VueAxios from 'vue-axios' Vue.use(VueAxios, axios); [...]// somecode axios.defaults.headers.common['Auth'] = localStorage.Auth; [...]//some code

then from the login method - in the axios.post('url').then(response=>{ // set the localstorage})

this will update the local storage and same as v-bind directive the global config will be updated and from now on the headers of all the requests will have this token.

Upvotes: 1

Related Questions