Victor Molina
Victor Molina

Reputation: 2641

Spotify API getting the error "No token provided" when fetching an endpoint

I am generating an access token every time the user tries to search a song with the spotify API beceuse I have seen that those token has an expiration time of 1h...

With the new access token I call the search endpoint but I get this response:

Object {
  "error": Object {
    "message": "No token provided",
    "status": 401,
  },
}

I don't have any idea why is that possible if I am passing the token to my GET request.

Here is the code:

export const searchMusic = async (query) => {
  // Get an access token
  const accessToken = await generateAccessToken();

  console.log(accessToken); // <---- This shows the access token "BQAM...YualK"

  // Request parameters
  const params = {
    q: query,
    type: "track,album",
  };

  // Request url
  const url = `https://api.spotify.com/v1/search${qs.stringify(params, {
    addQueryPrefix: true,
  })}`;

  const response = await fetch(url, {
    method: "GET",
    header: {
      Authorization: "Bearer " + accessToken, // <------- I pass the token as you can see here
    },
  });

  const data = await response.json();

  console.log(data); <----- Here comes the error
};

Does anybody knows what am I doing wrong? Also, is it bad to generate a new token everytime I try to fetch an endpoint? I mean, should I refresh it instead?

Thank you, I will really appreciate any guides.

Upvotes: 1

Views: 3715

Answers (2)

Victor Molina
Victor Molina

Reputation: 2641

For me, the problem was that I was using the api in the client, and my requirements needed to be run on the server... So, I moved my code to the server and all worked fine!

Upvotes: 1

justcodin
justcodin

Reputation: 1015

Maybe your API key isn't valid or doesn't give access to query that...

Code reference : https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401

Upvotes: 0

Related Questions