Jammming project in react section, Having trouble passing the access token

Hello everyone,

I am currently working on the jammming project in the react section of the full stack career path. Here is a link to the project: Jammming project

What happens first is that when I first click the search button, I am asked for access from Spotify and I accept. Now the app resets and I have to input my query again. When I click the search button, I get this error:

I post that the link show in the first error and I see this message:

After being stuck on this problem for such a long time, I decided to see the tutorial video to see what they did and implemented it. But I am still getting this error. I’m not sure why the token is getting lost. Here is my Spotify.js code that pertains to the fetch() issue:

let accessToken;
const clientID= '';
const redirectURI='http://localhost:3000/';

export const Spotify = {
    getAccessToken(){
        const accessTokenMatch = window.location.href.match(/access_token=([^&]*)/);
        const expiresInMatch = window.location.href.match(/expires_in=([^&]*)/);

        if(accessToken){
            return accessToken;
        }
        else if(accessTokenMatch 
                && expiresInMatch ) {
            accessToken = accessTokenMatch[1];
            
            let expiresIn = Number(expiresInMatch[1]); 
            window.setTimeout(() => accessToken = '', expiresIn * 1000);
            window.history.pushState('Access Token', null, '/');
            return accessToken;
                }

        else if(!accessToken && !window.location.href.match(/access_token=([^&]*)/)){
            window.location = `https://accounts.spotify.com/authorize?client_id=${clientID}&response_type=token&scope=playlist-modify-public&redirect_uri=${redirectURI}`;
        }
    },
    search(searchTerm){
        const passedAccessToken = Spotify.getAccessToken();
        console.log('This is the passed access token:' + passedAccessToken);
        console.log('this is the search term: ' + searchTerm)
        const endpoint = `https://api.spotify.com/v1/search?type=TRACK&q=${searchTerm}`;

        return fetch(endpoint,
            {headers:{Authorization: `Bearer ${passedAccessToken}`}
                }
            )
            .then(response=>{
                if(response.ok){
                return response.json();
                    }
                throw new Error('Request Failed!');},
                (networkError)=>{
                    console.log(networkError.message);
                })
            .then(jsonResponse => {
                if(!jsonResponse){
                    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}]);
            });

Could it be that the access token gets lost after the app restarts during the authorization process? I checked previous forum messages and someone said that perhaps the token gets lost when the app restarts after the authorization process. Here is that forum message: Jammming: Problem with getAccessToken method

By any chance could the reason be why I am getting this error is because I am out of the U.S.? Codecademy mentioned that perhaps this project may not work for people outside the U.S.

Any help is greatly appreciated! All the best and take care! Happy coding :slight_smile:

Hi @codejumper03379

Try passing the key as a string as in a JSON object:
{headers:{'Authorization': Bearer ${passedAccessToken}}

Did you edit your access token before posting it here? If not, better take it out as it shouldn’t be posted publicly.

2 Likes

Hi @mirja_t, I tried passing the key as a string in as a JSON object:

return fetch(endpoint,
            {headers:{'Authorization': `Bearer ${passedAccessToken}`}
                }
            )

But I still get the same error:

It seems that the token gets lost after the authorization process. Though I’m not sure. Also thanks for letting me know about my clientID. I’ve removed it from the post.

I don’t think that your token gets lost. I guess there is another issue in your request chain.

I’ve got ‘TRACK’ as lower case. If I change it to upper case in my code as you have it, I get the same error. So I guess that’s an issue.

1 Like

@ mirja_t, oh thank you so much! This was driving me crazy. I owe you a cup of coffee. Take care :slight_smile:

1 Like