Reputation: 9417
I want to use the Spotify API to retrieve a user's info. I've already figured out to get an access token
. First I get the authorization code from Spotify and I send that to and endpoint that generates an access token
, this looks as so...
const access = async (req, h) => {
// URL to retrieve an access token.
const spotify_url = "https://accounts.spotify.com/api/token";
// Send authorization code to spotify.
const response = await axios({
method: "post",
url: spotify_url,
params: {
grant_type: "authorization_code",
code: req.query.auth_code,
redirect_uri: process.env.REDIRECT_URI
},
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic " + (Buffer.from(process.env.CLIENT_ID + ":" + process.env.CLIENT_SECRET).toString("base64"))
}
})
.then(response => {
// Retrieve access and refresh tokens.
let access_token = response.data.access_token;
let response_token = response.data.refresh_token
return {
access_token: access_token,
response_token: response_token
}
})
...
...
return result
I didn't add all the code but it works perfectly. What is being returned is the access token
and the refresh token
.
I am using Hapi.js
so I am putting this in a pre
handler and sending the access token
to another handler/function which then uses the access token
to retrieve the user's information...
const user_account = async (access_token) => {
const user = await axios.get("https://api.spotify.com/v1/me", {
header: {
"Authorization": "Bearer " + access_token
}
})
.then(response => {
// Return the full details of the user.
return response;
})
.catch(err => {
throw Boom.badRequest(err);
});
return user;
}
The problem is that I am getting an 401
error.
UnhandledPromiseRejectionWarning: Error: Request failed with status code 401
It seems that my access token
might not be valid. That's the only thing I can think of, however, I checked and I am sending the same token that was generated by the first function, so it should be valid. Maybe the way I'm formatting my request is wrong. I can't figure out what the reason for this is.
Upvotes: 2
Views: 1727
Reputation: 33994
You have small typo error in axios.get request. Change header to headers
Change
header: {
"Authorization": "Bearer " + access_token
}
To
headers: {
"Authorization": "Bearer " + access_token
}
Upvotes: 2