You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 19:07:26