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

React应用无法从API Gateway获取响应的问题求助

问题解决:React调用API Gateway出现Failed to fetch错误

核心原因

你代码中设置的mode: 'no-cors'是触发错误的关键。在该模式下,浏览器会严格限制前端对响应内容的访问权限:

  • 无法读取response.ok、response.status等状态字段
  • 无法调用response.json()解析响应数据
  • 即便请求实际成功,前端也无法获取返回内容,最终抛出Failed to fetch错误

而Postman、浏览器直接访问、Python脚本不受浏览器同源策略约束,因此能正常请求接口。

修复步骤

  1. 移除mode: 'no-cors'配置
    删除fetch选项中的该参数,让浏览器使用默认的cors模式。
  2. 配置API Gateway的CORS规则
    在AWS API Gateway控制台中,检查对应阶段的CORS设置:
    • 允许的Origin需包含你的React应用域名(比如本地开发的http://localhost:3000)
    • 允许的Headers、Methods要匹配你的请求需求(如GET/POST、Content-Type等)
  3. 修改后的代码示例
function App() {
  const [faceLivenessAnalysis, setFaceLivenessAnalysis] = React.useState(null)
  const [sessionId,setSessionId] = React.useState(null)
  const [loading,setLoading] = React.useState(null)

  useEffect(() => {
    const fetchCreateLiveness = async () => {
        try {
             // 移除mode: 'no-cors'配置
             const response = await fetch('https://xxxx-api.us-east-1.amazonaws.com/dev');
            if (!response.ok) {
                throw new Error(`请求失败,状态码:${response.status}`);
            }
            const data = await response.json();
            const mockresponse= { sessionId:data.sessionId}
            setSessionId(mockresponse);
            setLoading(false);
            console.log('session:', data.sessionId);
        } catch (error) {
            console.error('Error fetching session ID:', error);
            setLoading(false);
        }
    };

    fetchCreateLiveness();
  }, []);
}

额外注意事项

  • 本地开发时,若遇到临时CORS问题,可在React项目的package.json中添加代理配置:"proxy": "https://xxxx-api.us-east-1.amazonaws.com",但生产环境必须依赖API Gateway的正式CORS配置。
  • 确认请求method与API Gateway的配置一致,比如接口是POST类型,而fetch默认使用GET的话也会触发错误。

内容的提问来源于stack exchange,提问作者PiaklA

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 16:42:10