代码之家  ›  专栏  ›  技术社区  ›  Eddie Martinez

在本地运行AWS SAM CLI时启用CORS

  •  1
  • Eddie Martinez  · 技术社区  · 5 年前

    每当我试图通过浏览器通过POST访问serverless lambda函数时,我都会得到一个错误

    当它是一个 /GET POST 这就是它失败的时候。

    sam local start-api

    还有我的模板.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?

    1 回复  |  直到 5 年前
        1
  •  6
  •   ngoctrambui    3 年前

    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. 将选项COR添加到模板.yaml
        Globals:
          Function:
            Timeout: 20
          Api:
            Cors:
              AllowMethods: "'GET,POST,OPTIONS'"
              AllowHeaders: "'content-type'"
              AllowOrigin: "'*'"
              AllowCredentials: "'*'"
    
    1. 更新中的属性资源函数模板.yaml
              Events:
                HelloWorld:
                  Type: Api 
                  Properties:
                    # Path: /hello
                    # Method: get
                    Path: "/{proxy+}"
                    Method: ANY
    
        2
  •  4
  •   user10682499    5 年前

        "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网关时,CORs由API网关上的配置处理。

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

    How to Enable CORS for an AWS API Gateway Resource

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

        3
  •  4
  •   me2resh    4 年前

    首先,您需要在模板.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");