How should I send JWT token in axios GET request?

Viewed 47569

I'm new to Vue.js and want to make a request in a component to a restricted api:

  computed: {
    token () {
      return this.$store.getters.getToken; 
    },
   ...

created () {
         axios
        .get( this.BASE_URL + '/profile/me')
        .then( res => {
                    this.profile = res.data;
                    console.log('profile is:', res.data);

          })
          .catch(error => console.log(error))            
    },

The problem is that I don't know how to include the token into the request header. So not surprisingly I get 401 error in response.

And when I try

axios.defaults.headers.common['Authorization'] = this.token;

before the get request I receive OPTIONS /profile/me instead of GET /profile/me in the server logs.

How can I fix it?

2 Answers

Axios get() request accept two parameter. So, beside the url, you can also put JWT in it.

axios.get(yourURL, yourConfig)
.then(...)

In your case yourConfig might be something like this

yourConfig = {
   headers: {
      Authorization: "Bearer " + yourJWTToken
   }
}

Also you can read about what you can put in your config here https://github.com/axios/axios. Just search for "Request Config"

This works for me, try like -

let JWTToken = 'xxyyzz';
 axios
    .get(this.BASE_URL + '/profile/me', { headers: {"Authorization" : `Bearer ${JWTToken}`} })
    .then(res => {
       this.profile = res.data;
       console.log('profile is:', res.data);
      })
      .catch(error => console.log(error)) 
Related