Hello, I just finished the final steps in Jamming project but I’m having difficulties in fixing the “INVALID_CLIENT” error on my side I don’t know why it does not fetch the API.
here’s my Spotify.js code:
const clientId = "a659494b83f74e7289950de6c356e4ba";
const redirectURI = "http://localhost:3000";
let accessToken;
const Spotify = {
getAccessToken() {
if (accessToken) {
return accessToken;
} else {
var accessTokenMatch = window.location.href.match(/access_token=([^&]*)/);
var expiresInMatch = window.location.href.match(/expires_in=([^&]*)/);
}
if (accessTokenMatch && expiresInMatch) {
accessToken = accessTokenMatch[1];
const expiresIn = Number(expiresInMatch[1]);
window.setTimeout(() => (accessToken = ""), expiresIn * 1000);
window.history.pushState("Access Token", null, "/");
return accessToken;
} else {
// The access token variable is empty and is not in the URL
const accessURL = `https://accounts.spotify.com/authorize?client_id=${clientId}&response_type=token&scope=playlist-modify-public&redirect_uri=${redirectURI}`;
window.location = accessURL;
}
},
search(term) {
const accessToken = Spotify.getAccessToken();
return fetch(`https://api.spotify.com/v1/search?type=track&q=${term}`, {
headers: { Authorization: `Bearer ${accessToken}` },
})
.then((response) => {
return response.json();
})
.then((jsonResponse) => {
if (!jsonResponse.tracks) {
return [];
}
return jsonResponse.tracks.items.map((track) => ({
id: track.id,
name: track.name,
artist: track.artists[0].name,
album: track.album.name,
uri: track.uri,
}));
});
},
savePlaylist(name, trackURIs) {
if (!name || !trackURIs.length) {
return;
}
const accessToken = Spotify.getAccessToken();
const headers = { Authorization: `Bearer ${accessToken}` };
let userID;
return fetch(`https://api.spotify.com/v1/me`, { headers: headers })
.then((response) => response.json())
.then((jsonResponse) => {
userID = jsonResponse.id;
return fetch(`https://api.spotify.com/v1/users/${userID}/playlists`, {
headers: headers,
method: "POST",
body: JSON.stringify({ name: name }),
})
.then((response) => response.json())
.then((jsonResponse) => {
const playlistId = jsonResponse.id;
return fetch(
`https://api.spotify.com/v1/users/${userID}/playlists/${playlistId}/tracks`,
{
headers: headers,
method: "POST",
body: JSON.stringify({ uris: trackURIs }),
}
);
});
});
},
};
export default Spotify;
Here’s the github link of my Spotify.js for the project:
** Frontend-Engineering-Path/Spotify.js at main · KeithRussel/Frontend-Engineering-Path · GitHub **