React食谱网站Map渲染失败及Spoonacular API 401错误求助
问题分析与解决方案
1. 401 Unauthorized 错误的核心原因
你的API请求URL用单引号包裹,但模板字符串的变量插值必须使用反引号(`),这直接导致API Key没有被正确注入,服务器识别到无效密钥后返回401错误。
修复后的请求代码:
const data = await fetch( `https://api.spoonacular.com/recipes/complexSearch?apiKey=${process.env.REACT_APP_API_KEY}&cuisine=${name}` );
同时需确认以下几点:
- 项目根目录存在
.env文件,且配置格式为REACT_APP_API_KEY=你的实际API密钥(React要求环境变量必须以REACT_APP_开头) - 重启开发服务器,确保环境变量被正确加载(React仅在启动时读取.env文件)
- 检查Spoonacular控制台,确认API Key有效且剩余调用额度充足
2. Map无法渲染内容的问题
当前map无内容是因为API请求失败后,recipes.results不存在,导致setCuisine(recipes.results)将cuisine设为undefined。即使添加了?避免报错,也没有数据可渲染。
除修复API请求外,建议添加错误处理逻辑,避免状态被错误覆盖:
const getCuisine = async (name) => { try { const data = await fetch( `https://api.spoonacular.com/recipes/complexSearch?apiKey=${process.env.REACT_APP_API_KEY}&cuisine=${name}` ); if (!data.ok) { throw new Error(`请求失败: ${data.status}`); } const recipes = await data.json(); setCuisine(recipes.results || []); // 确保即使results不存在,也设置为空数组 } catch (error) { console.error('获取食谱失败:', error); setCuisine([]); // 出错时重置为空数组,避免后续map报错 } };
额外优化建议
添加加载状态提升用户体验:
const [loading, setLoading] = useState(false); const getCuisine = async (name) => { setLoading(true); try { // 原有请求逻辑 } catch (error) { // 错误处理逻辑 } finally { setLoading(false); } }; // 组件返回部分补充加载提示 return ( <Grid> {loading ? <p>加载中...</p> : cuisine?.map((item) => ( <Card key={item.id}> <img src={item.image} alt={item.title} /> {/* 补充alt文本,符合无障碍规范 */} <h4>{item.title}</h4> </Card> ))} </Grid> );
内容的提问来源于stack exchange,提问作者raul atofanei
相关产品推荐
相关产品推荐

