0

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.

4
  • Look at the 2nd answer - stackoverflow.com/questions/36315389/… Aug 19, 2018 at 17:14
  • As I mention in the question. I've seen this approach, how I configure Vue.http.interceptors.push((request, next) => {// setting the header}); from the component?
    – Dav k
    Aug 19, 2018 at 18:13
  • These config overrides are global, so you'll have to set it outside of all components scope and it will apply to all XHR calls (for example - in app.js file) Aug 19, 2018 at 18:34
  • I'm sorry if I'm not clear, I understand what you say and yet don't know how to send the data (the token) to this config from the component. as I mention in the last sentence of my question.
    – Dav k
    Aug 19, 2018 at 20:54

1 Answer 1

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.