Jammming spotify connection problems (solution)

Hello everybody!

I hope I’m posting this in the right category. I’ve been cracking the Jammming project in the full stack developer course for a week now. And I’m hoping to save some of you some time coding this project. I followed allong with all the steps mentioned in the get-unstuck-video, however, nothing seemed to fix my projects problems.

I had problems with connecting a profile and connecting to that profile to save the playlist. After a week of searching and browsing the internet, I found a few problems with the code. If your stuck at the same bit as me, copy and paste the code below into your Spotify.js file.

I hope this works as well for you as it did for me!

Good luck!


const clientId = 'pasteyourclientidhere';

const redirectUri = 'http://localhost:3000/';

let accesToken;

const Spotify = {

    getAccesToken(){

        if(this.accesToken){

            return accesToken;

        }

        // check for acces token match

        const accesTokenMatch = window.location.href.match(/access_token=([^&]*)/);

        const expiresInMatch = window.location.href.match(/expires_in=([^&]*)/);

        if(accesTokenMatch && expiresInMatch){

            accesToken = accesTokenMatch[1];

            const expiresIn = Number(expiresInMatch[0]);

           

            //Clear params, to get new acces when token expires

            window.setTimeout(() => accesToken = '', expiresIn * 6000);

            //Line below basically deletes your acces token

            //window.history.pushState('Acces Token', null, '/');

            return accesToken;

        } else {

            //const accessUrl = `https://accounts.spotify.com/authorize?client_id=${clientId}&scope=playlist-modify-public&redirect_uri=${redirectUri}`;

            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 accesToken = Spotify.getAccesToken();

        const headers = {

            Authorization: `Bearer ${accesToken}`

        }

        return fetch(`https://api.spotify.com/v1/search?type=track&q=${term}` , {headers: headers}

        /* instead of {headers: headers}

        {

            headers: {

                Authorization: `Bearer ${accesToken}`

            }

           

        }*/).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){

            console.log('name and trakcuris not set');

            return;

        }

        const accesToken = Spotify.getAccesToken();

        //Uncomment line below to see acces token in the console

        //console.log(`savePlaylist() accesToken - ${accesToken}`);

        const headers = {

            Authorization: `Bearer ${accesToken}`

        }

        let userId;

        return fetch(`https://api.spotify.com/v1/me`, {headers: headers}

        ).then(response => response.json()

        ).then(jsonResponse => {

            userId = jsonResponse.id;

            //Uncomment line below to see user id in the console

            //console.log(`savePlaylist() userId - ${userId}`);

            //instead of  return fetch(`https://api.spotify.com/v1/me/users/${userId}/playlists`,

            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;
2 Likes

I found another Codecademy thread that addresses this problem. I struggled with it too. Hope this helps. Solution