Tichel
Tichel

Reputation: 531

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?

Upvotes: 1

Views: 1116

Answers (2)

Tichel
Tichel

Reputation: 531

I added the code from digital drifter, and solved the problem (with help) with changing the mounted function in Vue.

mounted () {
    console.log('mounted')
    UserProfileService.index()
      .then((res) => {
        this.user = res.data
      })
  }

Upvotes: 0

Brian Lee
Brian Lee

Reputation: 18187

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
}

Upvotes: 1

Related Questions