Hello everybody, I keep trying to make work the search part and the save to Spotify part of the jammming React project but it still doesn’t work. If you could look at the code and tell me what’s wrong please. There aren’t any errors thrown, the results just doesn’t print, it seems like there is no response from the spotify API.
Spotify.js :
let accessToken = '';
const clientId = 'd97479793d00499291557a164991793e';
const redirectUri = 'http://localhost:3000/';
const Spotify = {
getAccessToken(){
if (accessToken) {
return accessToken;
}
//Cherche le access token
let accessTokenFound = window.location.href.match(/access_token=([^&]*)/);
const expiresInMatch = window.location.href.match(/expires_in=([^&]*)/);
if(accessToken && expiresInMatch){
accessToken = accessTokenFound[1];
const expiresIn = Number(expiresInMatch[1]);
// Nettoyage afin de pouvoir avoir de nouvelles infos quand le temps est expire
window.setTimeout(() => { accessToken = '' ; }, expiresIn * 1000 );
window.history.pushState('Access Token', null, '/');
return accessToken;
} else {
window.location = 'https://accounts.spotify.com/authorize?client_id=' + clientId + '&response_type=token&scope=playlist-modify-public&redirect_uri=' + redirectUri;
}
},
search(term){
const accessToken = Spotify.getAccessToken();
let retour;
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 => {
return {
id: track.id,
name: track.name,
artist: track.artists[0].name,
album: track.album.name,
uri: track.uri }
});
});
},
savePlaylist(name,tracksArray){
if(!name && (!tracksArray || tracksArray.length > 99)){
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`, {method: name, headers:headers, body: JSON.stringify({name:name})}
).then(response =>
response.json()
).then(jsonResponse => {
let playlistId=jsonResponse;
return fetch( `https://api.spotify.com/v1/users/${userId}/playlists/${playlistId}/tracks` , {method:'POST', 'headers': headers, body:{'uris':tracksArray} }).then( response => {
return response.json();
});
});
});
}
}
export default Spotify;