React code encountering unexpected Spotify API response
P粉471207302
P粉471207302 2023-09-17 09:57:50
0
1
703

I'm making an app in React using Spotify API.

First, I get the access token using my clientID and clientSecret. Then I'm trying to get the userID using this token. The documentation mentions that you need to make a get request and pass the token as a header.

The problem is, I always get a 401 error code in response. The documentation mentions that this error may be because the token has expired. But in my code I am trying to get the userID immediately after getting the token.

My second question is about making requests in React. As you can see, I used the useEffect hook to achieve this, but I'm not sure if this is the correct approach. Also, the way I'm doing the second request doesn't feel right (if statement inside useEffect).

Any help is greatly appreciated!

P.S. apiKey and apiSecret are global variables, the first request worked fine, it returned a valid token, which was successfully used to make another get request to search for songs.

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

reply all(1)
P粉668113768

It looks like your code is on the right track, but the problem may have to do with how the token is handled and when the second request for the user ID is made. Furthermore, there is no need to use two useEffect hooks.

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();
}, []);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template