如何使用 AWS SAM 启用 CORS

2024-01-12

我正在尝试在我的 AWS SAM 应用程序中启用 CORS。这是我的片段template.yaml:

Globals:
  Api:
    Cors:
      AllowMethods: "'*'"
      AllowHeaders: "'*'"
      AllowOrigin: "'*'"

Resources:
  MyApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: prod
      Auth:
        Authorizers:
          MyCognitoAuthorizer: ...

  getByIdFunc:
    Type: AWS::Serverless::Function
    Properties:
      Handler: src/handler.handle
      Events:
        ApiEvent:
          Type: Api
          Properties:
            Path: /{id}
            Method: GET
            RestApiId: !Ref MyApi

根据这个将 CORS 与 AWS SAM 结合使用 https://stackoverflow.com/questions/50229563/using-cors-with-aws-sam然后https://github.com/aws/serverless-application-model/issues/373 https://github.com/aws/serverless-application-model/issues/373,cors 配置应该可以工作,但不幸的是,API 响应上没有设置标头,如下所示。

< HTTP/2 200 
< content-type: application/json
< content-length: 770
< date: Tue, 13 Apr 2021 19:55:31 GMT
< x-amzn-requestid: ...
< x-amz-apigw-id: ...
< x-amzn-trace-id: Root=1-...-...;Sampled=0
< x-cache: Miss from cloudfront
< via: 1.1 ...cloudfront.net (CloudFront)
< x-amz-cf-pop: FRA2-C2
< x-amz-cf-id: ...==
< 
* Connection #0 to host ....execute-api.eu-central-1.amazonaws.com left intact
[{"model": ..}]

我还尝试将 cors 配置添加到 API 定义 (MyApi) 本身,如中所述官方文档在这里 https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-property-api-corsconfiguration.html,但没有成功。

我可以自己在响应中添加标头,但我宁愿将其放在模板文件中。


为我解决这个问题的方法是将以下内容添加到我的 template.yaml 中:

Globals:
    Api:
        Cors:
            AllowMethods: "'GET,POST,OPTIONS'"
            AllowHeaders: "'content-type'"
            AllowOrigin: "'*'"
            # AllowCredentials: true  Uncomment only if you choose a specific origin instead of the * wildcard.

正如 nirvana124 和 Nitesh 所说,您还需要在每个端点中返回这些标头和响应:

return {
    statusCode: 200,
    headers: {
        "Access-Control-Allow-Headers" : "Content-Type",
        "Access-Control-Allow-Origin": "*", // Allow from anywhere 
        "Access-Control-Allow-Methods": "GET" // Allow only GET request 
    },
    body: JSON.stringify(response)
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 AWS SAM 启用 CORS 的相关文章

随机推荐