Reputation: 85
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
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
Reputation: 2827
It should be:
axios.get(`url`, { 'headers': { 'Authorization': this.AuthStr } })
Upvotes: 0
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