获取数据时出现 401 错误
useEffect(() => {
fetch(`https://api.unsplash.com/photos?client_id={accessKey}`)
.then((res)=>res.json())
.then(setImages);
}, [])
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]);