Pratik Solanki
Pratik Solanki

Reputation: 85

Using Axios GET with Authorization Header in vue App

I'm trying to use axios for a GET request with an API which requires an Authorization header.

here is my current code

My current code:

data () {
   return {
      listings: [],
      AuthStr : 'Bearer ' + JSON.parse(localStorage.getItem('token')),
   }
},
created () {
   axios.get(`url`, { 'headers': { 'Authorization': AuthStr } })
   .then((response => {
       this.listings = response.data;
   })
   .catch((error) => {
       console.log(error)
   })
}

it shows me 403 error I don't know why.

Upvotes: 1

Views: 14272

Answers (3)

Vijay Joshi
Vijay Joshi

Reputation: 959

You are using JSON.parse when getting the value for AuthStr. JSON.parse returns an object. Try removing it and if you are using the correct Auth token, it should work.

Upvotes: 0

Anuga
Anuga

Reputation: 2827

It should be:

axios.get(`url`, { 'headers': { 'Authorization': this.AuthStr } })

Upvotes: 0

Nasiruddin Saiyed
Nasiruddin Saiyed

Reputation: 1466

There are several ways to to add header to request.

For a single request:

let config = {
  headers: {
    Authorization: value,
  }
}


axios.get(URL, config).then(...)

you need to call data().AuthStr to get your token there is a typo.

Your created function will be

created () {
   axios.get(`url`, { 'headers': { 'Authorization': data().AuthStr } })
   .then((response) => {
       this.listings = response.data;
   })
   .catch((error) => {
       console.log(error)
   })
}

Upvotes: 2

Related Questions