Jamming - Can't get a valid Spotify Access Token

Hello everyone I’m struggling with getting results from the search of a song and it seems the error is due to invalid token access.

Here is the error: Failed to load resource: the server responded with a status of 401 ()

The following is my Spotify.js code

let accessToken = null;
let tokenExpirationTime = null;

const clientID = '1a4ea45a5e734a3f9753c2ea1c4c4ffc';
const redirectURI = 'http://localhost:3000/';

const Spotify = {
    getAccessToken() {
        if (accessToken && !this.isTokenExpired()) {
            return accessToken;
        }
        const urlAccessToken = window.location.href.match(/access_token=([^&]*)/);
        const urlExpiresIn = window.location.href.match(/expires_in=([^&]*)/);
        if (urlAccessToken && urlExpiresIn) {
            accessToken = urlAccessToken[1];
            const expiresIn = Number(urlExpiresIn[1]);
            tokenExpirationTime = new Date().getTime() + expiresIn * 1000;
            window.setTimeout(() => (accessToken = ''), expiresIn * 1000);
            window.history.pushState('Access Token', null, '/');
        } else {
            const redirect =`https://accounts.spotify.com/authorize?client_id=${clientID}&response_type=token&scope=playlist-modify-public&redirect_uri=${redirectURI}`;
            window.location = redirect;
        }
    },

    isTokenExpired() {
        if (!tokenExpirationTime) {
            return true;
        }
        const currentTime = new Date().getTime();
        return currentTime >= tokenExpirationTime;
    },

    search(term) {
        const 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(tracks => ({
                id: tracks.id,
                name: tracks.name,
                artist: tracks.artists[0].name,
                album: tracks.album.name,
                uri: tracks.uri,
            }));
        });
    },
};

export default Spotify;

I got the same problem. If i get it right I’ll let you know

alright so this is my code, I just added async before search then for my redirectURI I added the path to my to-be-called website aka url then added the url to my spotify api and finally deploy it with the correct name i chose as the url

const clientId = ‘6fab47f6fe6a46fc95678b97046a8a19’; // Insert client ID here.
const redirectUri = ‘https://bopping.surge.sh’; // Have to add this to your accepted Spotify redirect URIs on the Spotify API.
let accessToken;

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

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('Access Token', null, '/'); // This clears the parameters, allowing us to grab a new access token when it expires.
  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;
}

},

async search(term) {
const accessToken = Spotify.getAccessToken();
const response = await fetch(https://api.spotify.com/v1/search?type=track&q=${term}, {
headers: {
Authorization: Bearer ${accessToken}
}
});
const jsonResponse = await response.json();
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 => 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;

this worked for me and hopefully will for you.