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.

Dav k
  • 150
  • 1
  • 12
  • Look at the 2nd answer - https://stackoverflow.com/questions/36315389/configuration-for-vue-resource-root-and-authorization – Gal Weissman Aug 19 '18 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 '18 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) – Gal Weissman Aug 19 '18 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 '18 at 20:54

1 Answers1

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.

Dav k
  • 150
  • 1
  • 12