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

本地React应用调用AWS CloudFormation部署的API Gateway遇CORS错误

本地React应用调用AWS Serverless API Gateway遇CORS错误排查方案

问题说明

本地运行的React应用调用基于CloudFormation Stack、通过Infrastructure Composer构建的AWS Serverless API Gateway端点时触发CORS错误,尽管已在SAM模板中配置允许所有源(*),问题仍未解决。

前端调用代码

const fetchUser = async (userId) => {
  try {
    const response = await fetch(`https://<api-id>.execute-api.<region>.amazonaws.com/Prod/user/${userId}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        // 按需添加其他请求头
      }
    });
    if (!response.ok) {
      throw new Error('网络响应异常');
    }
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('请求错误:', error);
  }
};

现有SAM模板

Transform: AWS::Serverless-2016-10-31

Resources:
  UserApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: Prod
      DefinitionBody:
        openapi: '3.0'
        paths:
          /user/{userId}:
            get:
              x-amazon-apigateway-integration:
                httpMethod: GET
                type: aws_proxy
                uri: !Sub arn:${AWS::Partition}:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${DemoUserMgmt.Arn}/invocations
              responses: {}
      Cors:
        AllowMethods: "'GET,POST,OPTIONS'"
        AllowHeaders: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent'"
        AllowOrigin: "'*'" # 根据需要调整源

  DemoUserMgmt:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: src/function/user/UserManagement
      Handler: handler.handler
      Runtime: python3.12
      Events:
        UserApiGETuseruserId:
          Type: Api
          Properties:
            Path: /user/{userId}
            Method: GET
            RestApiId: !Ref UserApi

解决步骤

1. 在Lambda函数中手动添加CORS响应头

由于使用aws_proxy集成方式,API Gateway不会自动注入CORS头,必须在Lambda的返回结果中显式设置相关响应头。示例Python代码:

import json

def handler(event, context):
    # 业务逻辑处理
    user_data = {"userId": event["pathParameters"]["userId"], "name": "示例用户"}
    
    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-Amz-User-Agent'
        },
        'body': json.dumps(user_data)
    }

2. 修正SAM模板中的CORS配置引号问题

当前CORS配置的值多了一层不必要的单引号,会导致浏览器无法识别正确的源和方法。修正后的配置如下:

Cors:
  AllowMethods: "GET,POST,OPTIONS"
  AllowHeaders: "Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent"
  AllowOrigin: "*"

3. 确保OPTIONS预检请求被正确处理

对于手动定义的OpenAPI路径,需确认已添加OPTIONS方法的集成。也可以通过SAM自动生成OPTIONS方法,或者在API Gateway控制台检查对应路径是否存在OPTIONS方法,且集成能正确返回CORS头。

4. 重新部署SAM栈

修改配置和Lambda代码后,执行部署命令更新栈:

sam deploy --guided

5. 查看浏览器控制台的具体错误信息

通过浏览器开发者工具的控制台和网络面板,查看CORS错误的具体细节(比如预检请求失败、响应头缺失等),根据实际错误进一步调整配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 08:30:56