使用隐式 API 在 template.yaml 中的方法上启用 cors

Enabling cors on a method in the template.yaml with the implicit API

我试图在部署时为 Stack RestAPI 及其所有方法启用 Cors。我设法通过创建一个空模型手动完成,然后将其设置为响应以及 statusCode 200。

问题是,我不希望它被重置而必须手动更改它。到目前为止,我发现的最接近的是其他人提出的类似建议:

  OptionsMethod:
    Type: AWS::ApiGateway::Method
    Properties:
      AuthorizationType: NONE
      RestApiId: !Ref MyApi
      ResourceId: !GetAtt MyApi.RootResourceId
      ...

我已经尝试通过将 MyApi 替换为 ServerlessRestApi 来将其修改为我能想到的每一种风格,这似乎是隐含的 Rest Api。除了创建另一个 API 而不是隐式的,我不知道如何让它工作。

简而言之,我希望在部署 my/a 新 lambda 函数时默认启用 cors。

您可以在您的 yaml 中全局设置 CORS:

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

您必须在 Lambda 函数响应中包含 Cors headers(如 here 所述),更具体地说:

{
    body: {...},
    headers: {
        "Access-Control-Allow-Headers" : "X-Requested-With,Content-Type",
        "Access-Control-Allow-Origin": "https://www.example.com",
        "Access-Control-Allow-Methods": "OPTIONS,POST,GET"
}