React 代码中 Spotify API 没有预期响应

问题描述 投票:0回答:1

我正在使用 Spotify API 在 React 中制作应用程序。

首先,我使用 clientID 和 clientSecret 获取访问令牌。 然后,我尝试使用此令牌来获取用户ID。 文档说需要发出获取请求并将令牌作为标头传递。

问题是,我总是收到 401 代码响应。文档提到此错误可能是由于令牌已过期而发生的。但在我的代码中,我试图在获得令牌后立即获取用户ID。

我的第二个问题是关于在 React 中发出请求。正如您所看到的,我正在使用 useEffect 挂钩来执行此操作,但我真的不知道这是否是一个好的方法。此外,我发出第二个请求的方式感觉不太好(useEffect 中的 if 语句)。

如有任何帮助,我们将不胜感激!

附注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]);
javascript reactjs spotify
1个回答
0
投票

您的代码似乎走在正确的轨道上,但问题可能与令牌的处理方式以及何时发出第二个用户 ID 请求有关。另外,不需要使用两个

useEffect
挂钩。

    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();
}, []);
© www.soinside.com 2019 - 2024. All rights reserved.