1

我已经与 CORS 斗争了一段时间,但我已经没有想法了。我AWS::Serverless::HttpApi通过 SAM 进行了部署。这个 API 目前只有一个端点,它需要一个 POST 请求到/auctions. 在 PostMan 中测试它可以工作,但当然在其他任何地方进行测试都会引发可怕的preflight failed错误。在过去的几天里,我一直在尝试不同的东西,但没有任何效果。这是我的当前状态template.yaml

Resources:

  AdminApi:
    Type: AWS::Serverless::HttpApi
    Properties:
      CorsConfiguration:
        AllowMethods:
          - GET
          - POST
          - OPTIONS
        AllowOrigins:
          - "*"
        AllowHeaders:
          - "*"

  OptionsFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: ./src
      Handler: handlers/options.lambda_handler
      Runtime: python3.9
      Events:
        ApiPost:
          Type: HttpApi
          Properties:
            ApiId: !Ref AdminApi
            Path: /auctions
            Method: options

  CreateAuctionFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: ./src
      Handler: handlers/create_auction.lambda_handler
      Runtime: python3.9
      Events:
        ApiPost:
          Type: HttpApi
          Properties:
            ApiId: !Ref AdminApi
            Path: /auctions
            Method: post
      Environment:
        Variables:
          AUCTION_TABLE: !Sub "{{resolve:ssm:/applications/tikes/${Stage}/ddb/Auctions/TableName}}"
      Policies:
        - SSMParameterReadPolicy:
            ParameterName: !Sub "applications/tikes/${Stage}/*"
        - DynamoDBCrudPolicy:
            TableName: !Sub "{{resolve:ssm:/applications/tikes/${Stage}/ddb/Auctions/TableName}}"

这个模板有一个兄弟模板创建 DynamoDb 表,我省略了它,因为那部分工作正常。这是选项 lambda 处理程序(添加正文对标头没有影响):

def lambda_handler(event, context):
    return {
        'statusCode': 200,
    }

我从 POST 处理程序发送的成功响应:

def success_body(auction_id):
    return {
        'statusCode': 200,
        'body': json.dumps({
            'auction_id': auction_id
        }),
    }

在添加选项 lambda 处理程序之前,我收到了204来自 OPTIONS 请求的响应,没有允许来源标头,现在我添加了处理程序,我得到了200预期的结果,但是标头仍然不存在。使用此配置,通过 PostMan 发送具有相同标头的请求将在 POST 上具有标头,但在 OPTIONS 请求中将缺少该标头。

我尝试过的事情:

  1. CorsConfiguration: true
  2. 硬编码原点

我读过的东西:

  1. 修复 AWS API 网关不存在的 CORS“对预检的响应 ...”标头并放大
  2. https://aws.amazon.com/premiumsupport/knowledge-center/no-access-control-allow-origin-error/
  3. https://www.serverless.com/blog/cors-api-gateway-survival-guide/
  4. https://aws.amazon.com/blogs/compute/configuring-cors-on-amazon-api-gateway-apis/
  5. https://aws.amazon.com/premiumsupport/knowledge-center/api-gateway-cors-errors/
  6. https://github.com/aws/aws-sam-cli/issues/2637
  7. https://forums.aws.amazon.com/thread.jspa?threadID=252972
  8. 在 AWS Lambda HTTP API 网关集成上不可能实现 CORS
  9. 我能找到的任何其他 aws cors 问题。

POST 请求中存在标头的事实告诉我有些东西正在工作。我只是无法弄清楚为什么它适用于一个请求而不适用于另一个请求。

4

0 回答 0