遇到未預期的Spotify API回應的React程式碼
P粉471207302
P粉471207302 2023-09-17 09:57:50

我正在使用Spotify API在React中製作應用程式。

首先,我使用我的clientID和clientSecret取得存取權杖。 然後,我試圖使用此令牌來取得userID。文件中提到需要進行get請求並將令牌作為標頭傳遞。

問題是,我總是得到401錯誤代碼的回應。文件提到,這個錯誤可能是因為令牌已過期。但在我的程式碼中,我在獲得令牌後立即嘗試取得userID。

我的第二個問題是關於在React中進行請求。如您所見,我使用了useEffect鉤子來實現,但我不確定這是否是正確的方法。此外,我進行第二個請求的方式感覺不太好(在useEffect內部的if語句)。

非常感謝任何幫助!

P.S. apiKey和apiSecret是全域變量,第一個請求工作得很好,它返回有效的令牌,成功用於進行搜尋歌曲的另一個get請求。

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]);
P粉471207302
P粉471207302

全部回覆(1)
P粉668113768

看起來你的程式碼走在了正確的軌道上,但問題可能與令牌的處理方式以及何時進行第二次請求用戶ID有關。此外,沒有必要使用兩個useEffect鉤子。

const [userID, setUserID] = useState('');

useEffect(() => {
  // 获取访问令牌的函数
  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('获取访问令牌失败');
      }

      const data = await response.json();
      return data.access_token;
    } catch (error) {
      console.error('获取访问令牌时发生错误:', error);
      return null;
    }
  };

  // 获取用户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('获取用户ID失败');
        }

        const data = await response.json();
        setUserID(data.id);
      } catch (error) {
        console.error('获取用户ID时发生错误:', error);
      }
    }
  }; 

 getUserID();
}, []);
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!