I’m trying to create a new playlist using the Spotify API. I’ve set up authentication and received my access token, but the POST request for creating the playlist doesn’t complete. I’ve updated my code as per some suggestions and even tweaked it using axios, but the playlist never shows up and I don’t see any response in the console. I’m using Node.js version 12.14.1. Here’s an alternative code snippet I’ve attempted:
app.get('/makeNewPlaylist', function (req, res) {
console.log('token:', accessToken);
axios.post(
`https://api.spotify.com/v1/users/${userId}/playlists`,
{
name: 'My Cool Playlist',
public: true,
collaborative: false,
description: 'Created on ' + new Date().toLocaleString(),
},
{
headers: {
'Authorization': accessToken,
'Content-Type': 'application/json'
}
}
)
.then(response => console.log(response.data))
.catch(error => console.error('Error:', error));
});
What could be causing the POST request to hang?
I’ve encountered similar issues when working with the Spotify API. One aspect that immediately stands out is the use of your authorization header. Instead of passing the access token directly, you need to prefix it with ‘Bearer’. You can modify your headers as follows:
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json'
}
Additionally, verify that your userId is correct. If you’re uncertain, consider retrieving the current user’s profile using the ‘/me’ endpoint. Increasing error logging to capture detailed responses from Spotify may also provide further insights (e.g., logging error.response.data in your catch block).
I’ve been in your shoes before, and it can be frustrating when the API doesn’t respond as expected. One thing I noticed is that you’re not handling the response in your route. Instead of just logging, you should send a response back to the client. Try modifying your code like this:
app.get(‘/makeNewPlaylist’, async function (req, res) {
try {
const response = await axios.post(
https://api.spotify.com/v1/users/${userId}/playlists
,
{
name: ‘My Cool Playlist’,
public: true,
collaborative: false,
description: 'Created on ’ + new Date().toLocaleString(),
},
{
headers: {
‘Authorization’: Bearer ${accessToken}
,
‘Content-Type’: ‘application/json’
}
}
);
res.json(response.data);
} catch (error) {
console.error(‘Error:’, error.response ? error.response.data : error.message);
res.status(500).json({ error: ‘Failed to create playlist’ });
}
});
This way, you’ll get more detailed error information if something goes wrong. Also, double-check that your accessToken is still valid - they expire after a short time.