首页  >  问答  >  正文

遇到未预期的Spotify API响应的React代码

我正在使用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粉471207302P粉471207302369 天前616

全部回复(1)我来回复

  • P粉668113768

    P粉6681137682023-09-18 00:46:57

    看起来你的代码走在了正确的轨道上,但问题可能与令牌的处理方式以及何时进行第二次请求用户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();
    }, []);

    回复
    0
  • 取消回复