Jamming - 401 undefined Access Token

Good day to you who’s reading this!

Problem
I’m trying to complete the Jamming project but I’ve stumbled upon a problem using getAccessToken within the search method. The getAccessToken returns undefined, and if I’m not mistaken we can’t fetch anything with an header containing undefined values.

When i try using the search method I get this 401 error in the console:
> Spotify.js:31 GET https://api.spotify.com/v1/search?type=track&q=e 401
By logging Spotify.getAccessToken() to the console I get undefined

To be honest I’ve got no clue what’s causing this, so take a look at the code
Code:

const clientId = 'thisIsCorrect';
const redirectUri = 'http://localhost:3000/';
let accessToken;

const Spotify = {
    getAccessToken() {
        if (accessToken) {
            return accessToken;
        }

        // check for acces 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])
            //This clears the parameters, allowing us to grab a new access token when it expires
            window.setTimeout(() => accessToken = '', expiresIn * 1000);
            window.history.pushState('Access token', null, '/');
        } else {
            const accessUrl = `https://accounts.spotify.com/authorize?client_id=${clientId}&response_type=token&scope=playlist-modify-public&redirect_uri=${redirectUri}`;
            window.loaction = accessUrl;
            console.log(accessUrl)
        }
    },

    search(term) {
        const accessToken = Spotify.getAccessToken();
        console.log(accessToken)
        return fetch(`https://api.spotify.com/v1/search?type=track&q=${term}`,
            {
                headers: {
                    Authorization: `Bearer ${accessToken}`
                }
            }).then(response => {
                //console.log(response.json())
                return response.json()
            }).then(jsonResponse => {
                if (!jsonResponse.tracks) {
                    return []
                }
                return jsonResponse.tracks.items.map(track => ({
                    id: track.id,
                    name: track.name,
                    artist: track.artist[0].name,
                    album: track.album.name,
                    uri: track.uri
                }))
            }).catch(error => {
                console.log(error)
            })
    },

    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;

If you know what’s up here I’d love to hear what you have to say!

There are a few minor things you need to fix, but you’re really close right now.

The immediate issue you’re having is that it never gets redirected to Spotify to ask for authorization because of a typo here:

window.loaction = accessUrl;

Since it never redirects to Spotify, the call to Spotify.getAccessToken() in search() evaluates to undefined. Normally it would redirect to Spotify, request authorization from the user, and then Spotify would redirect back to your app with extra information in the URL. A search after that would get the access token from the URL so you can call the APIs.

You’re still going to have a couple things to debug after you fix that one typo, but you’ll be going in the right direction.

1 Like

Ough… Really?

Darn it, I hate to admit that you were able to spot my stupid mistake!
Thanks @selectall !