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

启用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正确。

问题根源

  1. Lambda代码语法错误:返回的headers对象存在两处语法问题:
    • Access-Control-Allow-Methods行末尾缺少逗号,导致JSON格式无效
    • 重复定义Content-Type字段
      这会导致Lambda执行失败,无法返回200状态码,浏览器的OPTIONS预请求得不到合法响应,触发CORS错误。
  2. 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);
  }
}

验证步骤

  1. 重新部署修正后的Lambda函数
  2. 重新部署API Gateway
  3. 刷新前端页面发起请求,确认CORS错误消失,数据正常返回

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 17:31:57