React应用无法从API Gateway获取响应的问题求助
问题解决:React调用API Gateway出现
Failed to fetch错误 核心原因
你代码中设置的mode: 'no-cors'是触发错误的关键。在该模式下,浏览器会严格限制前端对响应内容的访问权限:
- 无法读取
response.ok、response.status等状态字段 - 无法调用
response.json()解析响应数据 - 即便请求实际成功,前端也无法获取返回内容,最终抛出
Failed to fetch错误
而Postman、浏览器直接访问、Python脚本不受浏览器同源策略约束,因此能正常请求接口。
修复步骤
- 移除
mode: 'no-cors'配置
删除fetch选项中的该参数,让浏览器使用默认的cors模式。 - 配置API Gateway的CORS规则
在AWS API Gateway控制台中,检查对应阶段的CORS设置:- 允许的Origin需包含你的React应用域名(比如本地开发的
http://localhost:3000) - 允许的Headers、Methods要匹配你的请求需求(如GET/POST、Content-Type等)
- 允许的Origin需包含你的React应用域名(比如本地开发的
- 修改后的代码示例
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
相关产品推荐
相关产品推荐

