AWS SAM将cors配置为在本地运行

时间:2020-05-14 10:17:51

标签: aws-lambda serverless aws-sam

如何配置cors在本地运行lambda函数

我尝试了不同的方法,但无法获得适当的解决方案。

下面是我的template.yml

Resources:
  MyApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: dev
      Cors:
        AllowHeaders: "'Content-Type,Authorization,Origin,X-Requested-With,Accept,x-id-token,x-custom-header'"
        AllowOrigin: "'*'"
        AllowMethods: "'OPTIONS,POST,GET,PUT,DELETE'"
        AllowCredentials: "'*'"
      Auth:
        AddDefaultAuthorizerToCorsPreflight: False
        DefaultAuthorizer: MyLambdaTokenAuthorizer
        Authorizers:
          MyLambdaTokenAuthorizer:
            FunctionArn: !GetAtt MyAuthFunction.Arn

  HelloFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: functions/hello/handler.hello
      CodeUri: "."
      Events:
        HelloAPI:
          Type: Api
          Properties:
            Path: /hello
            Method: GET
            RestApiId: !Ref MyApi

这是我的处理函数

exports.hello = async (event) => {
    const response = {
        statusCode: 200,
        headers: {
            "Access-Control-Allow-Origin": "*", // Required for CORS support to work
            "Content-Type": "application/json",
            "Access-Control-Allow-Credentials": true, // Required for cookies, authorization headers with HTTPS
        },
        body: JSON.stringify({ message: "Hello World!" }),
    };

    callback(null, response);
};

仍然出现错误:

 No 'Access-Control-Allow-Origin' header is present on the requested resource.

1 个答案:

答案 0 :(得分:0)

尝试:

Resources:
  MyApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: dev
      Cors:
        AllowOrigin: "'*'"
        AllowHeaders: "'*'"
      Auth:
        AddDefaultAuthorizerToCorsPreflight: False
        DefaultAuthorizer: MyLambdaTokenAuthorizer
        Authorizers:
          MyLambdaTokenAuthorizer:
            FunctionArn: !GetAtt MyAuthFunction.Arn

  HelloFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: functions/hello/handler.hello
      CodeUri: "."
      Events:
        HelloAPI:
          Type: Api
          Properties:
            Path: /hello
            Method: get
            RestApiId: !Ref MyApi
        HelloAPIOptions:
          Type: Api
          Properties:
            Path: /hello
            Method: options
            RestApiId: !Ref MyApi

我更改了核心策略,并为OPTIONS /hello添加了一个端点。

相关问题