I'm a newer programmer using React.js and the Spotify API for a music app. I’m trying to access the Retry-After header in a 429 rate-limiting error response (Spotify docs here). This is my code currently, which I loosely copied from this article.
async getArtistArt (artistID) {
let url = `https://api.spotify.com/v1/artists?ids=${artistID}`
let response = await fetch(url, {
headers: {
'Authorization': 'Bearer ' + localStorage.getItem('accessToken')
},
});
let data = await response.json();
if (Object.keys(data)[0] === "error" && data.error.status === 429) { // Handle rate limiting
console.log('Error!');
console.log(data);
for (var pair of data.headers.entries()) {
console.log(pair);
console.log(pair[0]);
}
}
return data;
}
This is what I see in the console:
-
console.log('Error!');
// Logs 'Error!'console.log(data);
// Logs error object, but not the headerconsole.log(pair)
// Error that says 'Uncaught (in promise) TypeError: Cannot read property 'entries' of undefined'I've tried not putting the response into JSON but that seemed to have no effect.
I've tried to avoid try/catch error statements as I’ve heard they’re somewhat outdated and not usually recommended, but would I need them to access the response header?
I would be grateful for any advice.
I think I found where your error is. The code is almost correct except that you are checking for the headers in the json
of the response.
Try to do for (var pair of response.headers.entries()) {...}
, so that you are taking the response rather than its json
content.