Search code examples
vue.jsgetlocal-storageaxiostoken

Vue Axios local stored token is undefined


In Vue I am building a small Userprofile page. It is build on token-authentication using Axios. When mounting this page the token is undefined.

console.log

with login a token is placed in the localStorage.

The Axios Get request is build outside the Vue component

Api.js

import axios from 'axios'

export default () => {
  return axios.create({
    baseURL: `http://localhost:8081/`
  })
}

Get request

import Api from '@/services/Api'

let config = {
  headers: {
    'Content-Type': 'application/json',
    'Authorization': localStorage.getItem('token')
  }
}

export default {
  index () {
    return Api().get('user/profile', config)
  }
}

Vue

<script>
export default {
  data: () => ({
    user: {}
  }),
  mounted () {
    this.user = UserProfileService.index
    console.log(UserProfileService.config)
  }
}
</script>
There are many advices and I tried them all. With tics, with commas etc. Who sees the big picture?


Solution

  • Use a request interceptor to set the Authorization header:

    // Api.js
    export default () => {
      const instance = axios.create({
        baseURL: `http://localhost:8081/`
      })
    
      instance.interceptors.request.use(function (config) {
        const token = localStorage.getItem('token')
    
        if (token) {
          config.headers.Authorization = `Bearer ${token}`
        }
    
        return config
      }, function (error) {
        // Do something with request error
        return Promise.reject(error)
      })
    
      return instance
    }