joshk132
joshk132

Reputation: 1113

No token being sent with request

I have a Vuex action that gets run each time a page loads (not router.push), this function seems to run fine in the sense that it checks for a token and if the token exists it moves on. My issue is that I am dispatching another action which requires this token.

Okay so a bit clearer, I am using Axios with Vue.js to send API request. I have the authorization header set to a Vuex store value in my main.js file. I then have my App.uve load which triggers a default action to run which checks for the existance of a token (JWT). This default action also dispatches another action called storeUser which sends off a GET request to a user info API endpoint. When sending this user info API call I am seeing on my back end that it is not an authorized API call. Checking into the headers I need the authorization header is undefined. Below is what I believe to be the relavent code.

Default action that runs on App.vue load

tryAutoLogin({commit, dispatch}) {
  const token = localStorage.getItem('token')
  if(!token) {return}
    commit('authUser',{
    token
  })
  dispatch('storeUser')
},

second action that is causing the issue

storeUser({commit, state}, userData) {
  if(!state.token) return
  axios.get('/user/userInfo')
   .then(res => {
     console.log(res)
  })
   .catch(err => {
     console.log(err)
  })
},

main.js needed parts

import store from './store/store.js'
axios.defaults.headers.common['Authorization'] = store.token
new Vue({
  render: h => h(App),
  store,
  router
}).$mount('#app')

I cut out a ton in main.js to make it cleaner but those are the related parts to this issue. I don't think that there is anything else.

store.js state

state: {
  token: null,
  name: '',
  companyName: ''
},

Upvotes: 0

Views: 470

Answers (1)

joshk132
joshk132

Reputation: 1113

Thanks to Phil in the comments on the OP I have the below code working.

axios.interceptors.request.use(function (config) {
  config.headers.Authorization = store.state.token;
  return config;
}, function (error) {
  return Promise.reject(error);
});

Upvotes: 1

Related Questions