I'm trying to use axios for a GET request with an API which requires an Authorization
header.
My current code:
const AuthStr = 'Bearer ' + USER_TOKEN;
where USER_TOKEN
is the access token needed. This string concatenation may be the issue as if I post this as AuthStr = 'Bearer 41839y750138-391'
, the following GET request works and returns the data I'm after.
axios.get(URL, { 'headers': { 'Authorization': AuthStr } })
.then((response => {
console.log(response.data);
})
.catch((error) => {
console.log(error);
});
I also tried setting this as a global header with no success.
To send authorization header with Axios and JavaScript, we can set the headers property in the request options object. const response = await axios. get(url, { headers: { Authorization: `Bearer ${token}`, }, });
To send a GET request with a Bearer Token authorization header, you need to make an HTTP GET request and provide your Bearer Token with the Authorization: Bearer {token} HTTP header.
When you are using the Axios library and to pass custom headers, you need to construct headers as an object with the key name 'headers'. The 'headers' key should contain an object, here it is Content-Type and Authorization .
For anyone else that comes across this post and might find it useful... There is actually nothing wrong with my code. I made the mistake of requesting client_credentials type access code instead of password access code (#facepalms). FYI I am using urlencoded post hence the use of querystring.. So for those that may be looking for some example code.. here is my full request
Big thanks to @swapnil for trying to help me debug this.
const data = {
grant_type: USER_GRANT_TYPE,
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
scope: SCOPE_INT,
username: DEMO_EMAIL,
password: DEMO_PASSWORD
};
axios.post(TOKEN_URL, Querystring.stringify(data))
.then(response => {
console.log(response.data);
USER_TOKEN = response.data.access_token;
console.log('userresponse ' + response.data.access_token);
})
.catch((error) => {
console.log('error ' + error);
});
const AuthStr = 'Bearer '.concat(USER_TOKEN);
axios.get(URL, { headers: { Authorization: AuthStr } })
.then(response => {
// If request is good...
console.log(response.data);
})
.catch((error) => {
console.log('error ' + error);
});
Could not get this to work until I put Authorization in single quotes:
axios.get(URL, { headers: { 'Authorization': AuthStr } })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With