I figured this out and here's some help for my friends in the future who may be stuck (based on Google, I saw many were stuck):
- Axios is the tool to use to make requests to an API server such as Spotify's. Express is the tool to use if you want to listen and serve requests. This is the link that clarified it for me:
https://stackoverflow.com/questions/62244076/difference-between-express-js-and-axios-js-in-node#:~:text=Axios%20is%20used%20to%20send,an%20alternative%20to%20fetch().
- My goal here was to use Spotify's client credentials flow to send a POST request to Spotify's API servers and to get a access token that would allow me to use their API. Axios has this utility. I also want to make this function I write with async-await so that my function waits for the response before it returns it.
Here's the code I wrote that worked for me:
const axios = require('axios');
const qs = require('qs');
require('dotenv').config();
const client_id = process.env.SPOTIFY_API_ID; // Your client id
const client_secret = process.env.SPOTIFY_CLIENT_SECRET; // Your secret
const auth_token = Buffer.from(`${client_id}:${client_secret}`, 'utf-8').toString('base64');
const getAuth = async () => {
try{
//make post request to SPOTIFY API for access token, sending relavent info
const token_url = 'https://accounts.spotify.com/api/token';
const data = qs.stringify({'grant_type':'client_credentials'});
const response = await axios.post(token_url, data, {
headers: {
'Authorization': `Basic ${auth_token}`,
'Content-Type': 'application/x-www-form-urlencoded'
}
})
//return access token
return response.data.access_token;
//console.log(response.data.access_token);
}catch(error){
//on fail, log the error in console
console.log(error);
}
}
Note:
- Make sure to stringify the grant-credentials before sending it. Don't use the 'querystring' dependency. Use the newer 'qs' dependency. Works the same.
- Use 'dotenv' to make Node.js environment variables to protect your sensitive data like I did! May help further when you push to GitHub and just add the .env to the files to be ignored in your .gitignore file!
- Axios has some confusing documentation especially for beginners like me trying to use API's with such authentication flows. Here's are some links that helped me understand and structure my code (along with a lot of testing and failing):
https://flaviocopes.com/axios-send-authorization-header/
https://flaviocopes.com/node-axios/