API OAuth 错误:访问令牌在 React 中无效

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

获取数据时出现 401 错误

useEffect(() => {    
  fetch(`https://api.unsplash.com/photos?client_id={accessKey}`)
  .then((res)=>res.json())
  .then(setImages);
  }, [])
javascript reactjs api fetch
1个回答
0
投票

401 错误通常表示身份验证问题,与您在 API 中使用的 OAuth 访问令牌相关。确保您没有超出 API 速率限制。如果您在短时间内发出太多请求,API 可能会响应 401 错误。

您还可以修改 fetch 调用以更明确地处理错误。

useEffect(() => {    
  fetch(`https://api.unsplash.com/photos?client_id=${accessKey}`)
    .then((res) => {
      if (!res.ok) {
        throw new Error(`HTTP error! Status: ${res.status}`);
      }
      return res.json();
    })
    .then(setImages)
    .catch(error => console.error('Error fetching images:', error));
}, [accessKey]);
© www.soinside.com 2019 - 2024. All rights reserved.