繁体   English   中英

当我尝试对 CORS 预检 (Lambda) 使用方法 OPTIONS 时,AWS cloudformation template.yml 失败

[英]AWS cloudformation template.yml fails when I try to use method OPTIONS for CORS preflight (Lambda)

我尝试为方法 OPTIONS 添加一个块以接受并转发到我的 lambda 代理还有 OPTIONS 事件。 但是 cloudformation 失败了——但我找不到详细的原因。

这是我试过的块:

    CorsPreflightEvent:
      Type: Api
      Properties:
        Path: /
        Method: options
        Auth:
          Authorizer: NONE

这是完整的块:

  MyApp:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: !Sub 'awscodestar-${ProjectId}-lambda-01'
      Handler: index.handler
      Runtime: python3.9
      Timeout: 10
      Role:
        Fn::GetAtt:
        - LambdaExecutionRole
        - Arn
      Events:
        CorsPreflightEvent:
          Type: Api
          Properties:
            Path: /
            Method: options
            Auth:
              Authorizer: NONE
        GetEventAll:
          Type: Api
          Properties:
            Path: /
            Method: get
        GetEventSectionCat:
          Type: Api
          Properties:
            Path: /{subject}/{category}
            Method: get
        PostEvent:
          Type: Api
          Properties:
            Path: /
            Method: post

一般来说,我想允许没有 CORS 的选项。所以我在我的 python 中添加了一个选项响应。 我想它应该工作。 但它应在任何路径上作出反应。 这就是为什么我之前也尝试过这条路:

/{proxy+}

我想为任何请求禁用 CORS,但 chrome 抱怨,这就是为什么我尝试在我的 Python 中发送这个 header - 这应该针对所有类型的请求完成:

headers = {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'OPTIONS,POST,GET'
          }

有没有人看到我的 template.yml 有什么问题以及为什么“GenerateChangeSet”步骤可能会失败?


与此同时,我切换到一个更简单的解决方案来禁用 cors。不是通过代码而是在 template.yml 中我添加了这个块:

Globals:
  Api:
    Cors:
      AllowMethods: "'OPTIONS,POST,GET'"
      AllowHeaders: "'*'"
      AllowOrigin: "'*'"

这个线程帮助我找到了问题。

提到了一个工具: cfn-lint ,它能够给我一个有用的错误信息:

E0001 转换模板时出错:ID 为 [MyApp] 的资源无效。 ID 为 [CorsPreflightEvent t] 的事件无效。 无法在路径 [/] 的 API 方法 [选项] 上设置 Authorizer,因为在指定 API 上的 DefaultAuthorizer 时,“NONE”只是一个有效值。

所以我删除了Auth部分。 现在它经历了流水线过程。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM