Spotify '401 status, No token provided' when making POST request

Viewed 24

I've been stumped on what seems should have a simple solution, when making a call to the spotify api. What I've done is create a webapp which allows a user to search for songs hosted on spotify and add them to a queue of songs to play next. The process of building this app was going smoothly, users can search for tracks or artists and be met with results related to their search. The problem arises when attempting to add a selected track to the user's playback queue. I'm confused as to why I can perform GET requests, but fail to perform PUT or POST requests.

The spotify api requires user authentication for acquiring an access token, which is further used to perform these requests.

function to retrieve an access token

const ClientID = process.env.SPCID;
const ClientSecret = process.env.SPSID;
const refresh_token = process.env.RURI;

const basic = Buffer.from(`${ClientID}:${ClientSecret}`).toString("base64");
const TOKEN_ENDPOINT = `https://accounts.spotify.com/api/token`;

export const getAuth = async () => {
  const headers = {
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      Authorization: `Basic ${basic}`,
    },
    auth: {
      username: ClientID,
      password: ClientSecret,
    },
  };
  const data = {
    grant_type: "refresh_token",
    refresh_token: refresh_token,
  };

  try {
    const response = await axios.post(
      TOKEN_ENDPOINT,
      qs.stringify(data),
      headers
    );
    return response.data.access_token;
  } catch (error) {
    console.log(error);
  }
};

function to search for tracks/artists works as expected

const SEARCH_SONG_ENDPOINT = "https://api.spotify.com/v1/search?q=";

export const searchSong = async (query) => {
  const access_token = await getAuth();

  return axios.get(SEARCH_SONG_ENDPOINT + query + "&type=track%2Cartist", {
    headers: {
      Authorization: `Bearer ${access_token}`,
      "Content-Type": "application/json",
    },
  });
};

function to add modify playback (add track to queue) is similar but throws status 401, No Token Provided

const QUEUE_SONG_ENDPOINT = "https://api.spotify.com/v1/me/player/queue?uri=";

export const queueSong = async (song) => {
  const access_token = await getAuth();
  console.log(song);

  return axios.post(QUEUE_SONG_ENDPOINT + song, {
    headers: {
      Authorization: `Bearer ${access_token}`,
      "Content-Type": "application/json",
    },
  });
};

It's a peculiar problem thats been driving up the wall for 2 days now.

When checking the dev tools network requests the payload does indeed contain the access token and the query params do have the track intended to be added to the queue, meaning all of the pieces are there for this puzzle.

If anyone has any insight on what I could be doing wrong, any assistance would be appreciated.

Edit: The scope i'm using are also correct for the given requests I'm trying to perform

0 Answers
Related