AWS SAM:请求的资源响应上不存在“ Access-Control-Allow-Origin”标头

时间:2018-07-05 17:36:23

标签: cors aws-lambda aws-api-gateway amazon-cloudformation aws-sam-cli

我正在努力获得一个静态网站,以使用CORS调用API网关。我已经使用SAM本地运行下面的代码,但是在尝试从我的静态网站(本地托管)使用jQuery调用我的API时遇到以下CORS错误:

Failed to load http://localhost:3000/notify: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4000' is therefore not allowed access.

我的template.yaml

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Globals:
  Api:
    # enable CORS; to make more specific, change the origin wildcard
    # to a particular domain name, e.g. "'www.example.com'"
    Cors: "'*'"

Parameters:
  RecaptchaSecret:
    Type: String

Resources:
  NotifierFunction:
    Type: AWS::Serverless::Function 
    Properties:
      CodeUri: notifier/build
      Handler: app.lambda_handler
      Runtime: python3.6
      Environment: 
        Variables:
          PARAM1: VALUE
      Events:
        Notify:
          Type: Api 
          Properties:
            Path: /notify
            Method: post

Outputs:
    NotifierApi:
      Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/notify/"
    NotifierFunction:
      Value: !GetAtt NotifierFunction.Arn
    NotifierFunctionIamRole:
      Value: !GetAtt NotifierFunctionRole.Arn

我对SAM中的Globals部分的理解是,它应该将Api字段应用于我的(推断的)API网关。

我在网上看到了带有API网关的CORS的一些示例,其他示例使用了标准API网关模板,还有一些人除了使用大张旗鼓的文件之外还使用了SAM,但是我一直看不到成功的示例有人使CORS可以在没有摇摇欲坠的文件的情况下使用SAM工作(请参阅以下参考资料)。我觉得我肯定想念一些明显的东西!

我使用的是来自jQuery的常规POST请求,我可以发布前端代码,也可以发布“已编译的” CloudForamtion(如果有帮助的话)。

非常感谢您的帮助!

干杯:)

我看过的参考文献:

这是我的功能代码:

import json
import boto3
import requests

def lambda_handler(event, context):
    print "REACHED"
    print event
    ip = requests.get('http://checkip.amazonaws.com/')

    return {
        "statusCode": 200,
        "headers": {"Access-Control-Allow-Origin": "*"},
        "body": json.dumps({
            'message': 'hello world',
            'location': ip.text.replace('\n', ''),
        })
    }

1 个答案:

答案 0 :(得分:0)

如果您仍然对如何实现此目标感兴趣,可以按照以下说明通过cloudformation模板直接完成,最好的方法是在发布子资源之前定义一个根模拟资源。

  MockMethod:
    Type: 'AWS::ApiGateway::Method'
    Properties:
      AuthorizationType: NONE
      RestApiId: STRING
      ResourceId: STRING
      HttpMethod: OPTIONS
      Integration:
        Type: MOCK
        IntegrationResponses:
          - StatusCode: 200 
            ResponseParameters:
              method.response.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'"
              method.response.header.Access-Control-Allow-Methods: "'POST,OPTIONS'"
              method.response.header.Access-Control-Allow-Origin:* #Note * allows all origins
            SelectionPattern: 2\d{2}
            ResponseTemplates: 
              application/json: Empty
        PassthroughBehavior: WHEN_NO_MATCH
        RequestTemplates:
          application/json: '{"statusCode": 200}'
      MethodResponses:
        - ResponseModels:
            application/json: Empty
          ResponseParameters:
            method.response.header.Access-Control-Allow-Headers: true
            method.response.header.Access-Control-Allow-Methods: true
            method.response.header.Access-Control-Allow-Origin: true
          StatusCode: 200

请注意,OPTIONS是在POST方法之前处理起飞前CORS请求的功能。此外,如果您按照以下方式使用AWS_PROXY,则需要在lambda函数中处理标头CORS响应。

  POSTmethod: 
    Type: AWS::ApiGateway::Method 
    Properties:  
      HttpMethod: POST 
      RestApiId: STRING
      ResourceId: STRING
      Integration: 
        Type: AWS_PROXY 
        ConnectionType: INTERNET 
        IntegrationHttpMethod: POST 
        Credentials: STRING
        Uri: STRING
        PassthroughBehavior: WHEN_NO_TEMPLATES
        TimeoutInMillis: 10000 #Timeout in 10seconds  
      MethodResponses:
        - StatusCode: 200
          ResponseModels:
            application/json: Empty
          ResponseParameters:
              method.response.header.Access-Control-Allow-Headers: true
              method.response.header.Access-Control-Allow-Origin: true
        - StatusCode: 400
          ResponseModels:
            application/json: Empty

  OPTIONSmethod:
    Type: 'AWS::ApiGateway::Method'
    Properties:
      AuthorizationType: NONE
      RestApiId: STRING
      ResourceId: STRING
      HttpMethod: OPTIONS
      Integration:
        Type: MOCK
        IntegrationResponses:
          - StatusCode: 200 
            ResponseParameters:
              method.response.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,x-api-key,X-Amz-Security-Token'"
              method.response.header.Access-Control-Allow-Methods: "'POST,OPTIONS'"
              method.response.header.Access-Control-Allow-Origin: "'*'"
            SelectionPattern: 2\d{2}
            ResponseTemplates: 
              application/json: Empty
        PassthroughBehavior: WHEN_NO_MATCH
        RequestTemplates:
          application/json: '{"statusCode": 200}'
      MethodResponses:
        - ResponseModels:
            application/json: Empty
          ResponseParameters:
            method.response.header.Access-Control-Allow-Headers: true
            method.response.header.Access-Control-Allow-Methods: true
            method.response.header.Access-Control-Allow-Origin: true
          StatusCode: 200