English 中文(简体)
反应代码中未预期反应
原标题:Not expected response from Spotify API in React code

我正在使用 Spotify普森作读。

First, I obtain access token using my clientID and clientSecret. Then, I am trying to use this token to obtain userID. Documentation says that one needs to make get request and pass token as header.

问题在于,我总是有401部法典。 文件提到,这一错误可能是由于被证明已经过期。 但是,在我的法典中,我试图在我被打脚踢后立即获得用户信息数据库。

我的第二个问题是要求重新处理。 如你所看到的那样,我正在利用“效果”来做这项工作,但我并不真正知道这是好的做法。 此外,我提出第二次请求的方式并不真正感到 n(如果说在使用效果中的话)。

感谢任何帮助!

P.S. apiKey and apiSecret are global factors, and first request work Justvy, it reable token, which is amended used to make another receive request for searching歌曲.

const [token, setToken] = useState("");
const [userID, setUserID] = useState("");

// Obtain access token and user ID
useEffect(() => {
  // Get access token
  const parameters = {
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
    },
    body: `grant_type=client_credentials&client_id=${apiKey}&client_secret=${apiSecret}`,
  };

  fetch("https://accounts.spotify.com/api/token", parameters)
    .then((response) => {
      return response.json();
    })
    .then((data) => {
      setToken(data.access_token);
      return data.access_token;
    });
}, []);

// Obtain user ID once token is obtained
useEffect(() => {
  if (token != "") {
    const parameters = {
      method: "GET",
      headers: {
        Authorization: `Bearer ${token}`,
      },
    };

    fetch("https://api.spotify.com/v1/me", parameters)
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        console.log(data);
      });
  }
}, [token]);
问题回答

It seems like your code is on the right track, but the issue might be related to how the token is being handled and when the second request for the user ID is being made. Also in there no need to use two useEffect hooks.

    const [userID, setUserID] = useState(  );

useEffect(() => {
  // Function to obtain access token
  const getAccessToken = async () => {
    try {
      const response = await fetch( https://accounts.spotify.com/api/token , {
        method:  POST ,
        headers: {
           Content-Type :  application/x-www-form-urlencoded ,
        },
        body: `grant_type=client_credentials&client_id=${apiKey}&client_secret=${apiSecret}`,
      });
      
      if (!response.ok) {
        throw new Error( Failed to fetch access token );
      }

      const data = await response.json();
      return data.access_token;
    } catch (error) {
      console.error( Error fetching access token: , error);
      return null;
    }
  };

  // Function to obtain user ID
  const getUserID = async () => {
    const accessToken = await getAccessToken();
    
    if (accessToken) {
      try {
        const response = await fetch( https://api.spotify.com/v1/me , {
          method:  GET ,
          headers: {
             Authorization : `Bearer ${accessToken}`,
          },
        });

        if (!response.ok) {
          throw new Error( Failed to fetch user ID );
        }

        const data = await response.json();
        setUserID(data.id);
      } catch (error) {
        console.error( Error fetching user ID: , error);
      }
    }
  }; 

 getUserID();
}, []);




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签