【问题标题】:Enable CORS when running AWS SAM CLI locally在本地运行 AWS SAM CLI 时启用 CORS
【发布时间】:2019-04-18 03:21:49
【问题描述】:

每当我尝试通过浏览器通过 POST 访问无服务器 lambda 函数时,我都会收到错误消息

对预检请求的响应未通过访问控制检查:否>请求的资源上存在“Access-Control-Allow-Origin”标头。

当它是/GET 时,它工作正常我读过它是因为它没有发送飞行前请求。当我将其更改为 POST 时,它会失败。

我正在运行的命令:

sam local start-api

而我的 template.yaml 是:

...

Resources:
    PropertiesFunction:
        Type: AWS::Serverless::Function
        Properties:
            CodeUri: target/service-0.0.1-SNAPSHOT.jar
            Handler: com.aws.PropertiesHandler::handleRequest
            Runtime: java8
            Events:
                PropertiesApi:
                    Type: Api
                    Properties:
                        Path: /properties
                        Method: post

...

如何在这些端点上启用 CORS?

【问题讨论】:

    标签: amazon-web-services aws-lambda aws-api-gateway serverless aws-sam-cli


    【解决方案1】:

    我遇到了同样的错误,我已经分 3 步修复了它。 (Java8 中的 AWS Lambda,SAM CLI v0.37.0)

    1. 为您的标题添加选项:
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("X-Custom-Header", "application/json");
        headers.put("Access-Control-Allow-Origin", "*");
        headers.put("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE");
        headers.put("Access-Control-Allow-Headers", "X-Requested-With,content-type");
    
    1. 将选项 Cors 添加到 template.yaml 中
        Globals:
          Function:
            Timeout: 20
          Api:
            Cors:
              AllowMethods: "'GET,POST,OPTIONS'"
              AllowHeaders: "'content-type'"
              AllowOrigin: "'*'"
              AllowCredentials: "'*'"
    
    1. 更新 template.yaml 中的属性资源函数
              Events:
                HelloWorld:
                  Type: Api 
                  Properties:
                    # Path: /hello
                    # Method: get
                    Path: "/{proxy+}"
                    Method: ANY
    

    【讨论】:

    • 你拯救了我的一天。我的 YAML 几乎相同,但在 lamda 中我缺少标题,所以在添加标题后它对我有用。
    【解决方案2】:

    首先,您需要在 template.yml 中添加以下部分以在 API 网关中启用 cors:

    Globals:
      Api:
        Cors:
          AllowMethods: "'GET,POST,OPTIONS'"
          AllowHeaders: "'content-type'"
          AllowOrigin: "'*'"
          AllowCredentials: "'*'"
    

    然后在你的 lambda 函数响应中

    
            MultivaluedMap<String, Object> headers = responseContext.getHeaders();
    
            headers.add("Access-Control-Allow-Origin", "*");
            headers.add("Access-Control-Allow-Headers", requestContext.getHeaderString("Access-Control-Request-Headers"));
            headers.add("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,HEAD,OPTIONS");
    

    【讨论】:

    • 非常感谢您的回答!昨天在找到这个问题的答案时遇到了一些麻烦。
    【解决方案3】:

    您应该能够通过在处理程序函数中将以下标头显式添加到响应中来解决此问题以进行本地测试:

        "Access-Control-Allow-Origin": "*"
    

    您可以使用仅在本地运行时添加标头的环境变量。

    这是一个来自我拥有的处理函数的简单 Python 示例:

       if not all(field in values for field in required_fields):
        response = {
            'statusCode': 400,
            'body': json.dumps(
                {
                    'message': 'Required data missing from request body'
                }
            )        
        }
        # explicitly add CORs headers for local testing
        response['headers'] = {"Access-Control-Allow-Origin": "*"}
        return response
    

    这仅适用于本地测试,当您部署到 API 网关时,COR 由 API 网关上的配置处理。

    这个解决方案对我有用,直到我还使用 Cognito 用户池向 API 添加了授权,我目前正在尝试解决这个问题。

    这里有一篇关于这个问题的类似帖子: How to Enable CORS for an AWS API Gateway Resource

    Here's reference to it in the official AWS documentation.

    【讨论】:

    • 添加身份验证后你有没有运气 - 不幸的是我在同一点上。
    • 我也即将添加身份验证,但遇到了 CORS 错误。你有过什么运气吗?
    【解决方案4】:

    如果您使用的是 SAM,请在您的无服务器模板文件上尝试此操作

    "Globals": {
        "Api": {
          "Cors": {
            "AllowMethods": "'POST, GET, PUT, DELETE'",
            "AllowHeaders": "'content-type'",
            "AllowOrigin": "'*'"
          }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-08-30
      • 1970-01-01
      • 2021-06-03
      • 1970-01-01
      • 2021-07-07
      • 1970-01-01
      • 2022-10-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多