Hello everybody,
I am working on Jamming project from Full-stack developer career path and I am stuck at 95 step.
When I try creating the new playlist and add tracks in that playlist, I get this error:
I was searching all over the internet to find a solution, but without any luck
This is my code, like it is also in the video tutorial:
Spotify.js
const clientId = 'XXXXXX';
const redirectUri = 'http://localhost:3000/';
let accessToken;
const Spotify = {
getAccessToken() {
if (accessToken) {
return accessToken;
}
//check for access token match
const accessTokenMatch = window.location.href.match(/access_token=([^&]*)/);
const 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('Acces Token', null, '/');
return accessToken;
}
else {
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) {
let 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 => { return response.json()}
).then(jsonResponse => {
userId = jsonResponse.id;
return fetch(`https://api.spotify.com/v1/me/users/${userId}/playlists`,
{
headers: headers,
method: 'POST',
'Content-Type': 'application/json',
body: JSON.stringify( {name : name})
}).then(response => {
console.log(response);
return response.json() ;
}
).then (jsonResponse => {
const playlistId = jsonResponse.id;
return fetch(`https://api.spotify.com/v1/playlists/${playlistId}/tracks`,
{
headers: headers,
method: 'POST',
'Content-Type': 'application/json',
body: JSON.stringify( {uris: trackUris})
});
});
});
}
}
export default Spotify;
And here is App.js savePlaylist function:
savePlaylist() {
const trackURIs = this.state.playlistTracks.map(track => track.uri);
Spotify.savePlayList(this.state.playlistName, trackURIs).then(() => {
this.setState( {
playlistName: 'New Playlist',
playlistTracks: []
})
}).catch((rej) => {console.log(rej); })
}
I assume is something wrong on Spotify.js, with fetch POST, but I couldn’t see any misspelling.
Could you please have a look and help me?
Thank you all!