启用API Key后React前端无法通过Axios调用AWS API Gateway
启用API Key后React前端请求AWS API Gateway报CORS错误的解决方案
问题情况
未启用API Key时,React前端请求AWS API Gateway正常;启用API Key后,前端请求失败,浏览器报错:
Access to XMLHttpRequest at 'https://bvoj5hykj0.execute-api.us-east-1.amazonaws.com/test/testresource' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
Postman测试无论是否携带API Key均可正常响应,已确认API Key和URL正确。
问题根源
- Lambda代码语法错误:返回的headers对象存在两处语法问题:
Access-Control-Allow-Methods行末尾缺少逗号,导致JSON格式无效- 重复定义
Content-Type字段
这会导致Lambda执行失败,无法返回200状态码,浏览器的OPTIONS预请求得不到合法响应,触发CORS错误。
- API Gateway预请求处理缺失:浏览器发送的OPTIONS预请求默认会被API Gateway拦截,若未配置OPTIONS方法允许无API Key访问,会导致预请求失败。
修复方案
1. 修正Lambda代码
修复语法错误,同时添加OPTIONS预请求的处理逻辑:
import json def lambda_handler(event, context): # 处理OPTIONS预请求 if event['httpMethod'] == 'OPTIONS': return { 'statusCode': 200, 'headers': { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Headers": "Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,x-api-key", "Access-Control-Allow-Methods": "GET,OPTIONS" }, 'body': json.dumps('') } # 处理GET业务请求 return { 'statusCode': 200, 'headers': { "Access-Control-Allow-Origin": "*", "Content-Type": "application/json", "Access-Control-Allow-Headers": "Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,x-api-key", "Access-Control-Allow-Methods": "GET" }, 'body': json.dumps("changes saved") }
2. 配置API Gateway允许OPTIONS请求无API Key访问
- 登录AWS控制台进入API Gateway
- 找到目标API和对应资源,进入OPTIONS方法的设置页面
- 在Method Request模块中,将API Key Required设置为
false - 重新部署API到对应阶段
3. 确认React Axios请求的Header正确性
确保请求携带的x-api-key头格式正确,示例代码:
async function testAct() { try { const response = await axios.get("https://bvoj5hykj0.execute-api.us-east-1.amazonaws.com/test/testresource", { headers: { "x-api-key": "你的API Key" } }); console.log(response); setTestRes(response.data); } catch (error) { console.log(error); } }
验证步骤
- 重新部署修正后的Lambda函数
- 重新部署API Gateway
- 刷新前端页面发起请求,确认CORS错误消失,数据正常返回
内容的提问来源于stack exchange,提问作者DEBASISH MOHANTY
相关产品推荐
相关产品推荐

