【问题标题】:PUT/POST/DELETE: 403 error forbidden + CORS error with AWS SAMPUT/POST/DELETE:403 错误禁止 + AWS SAM 的 CORS 错误
【发布时间】:2019-04-02 03:12:48
【问题描述】:

我想做一个简单的 HTTP 请求,但被这些错误阻止:

zone.js:2969 选项http://127.0.0.1:3000/project/new 403(禁止)

从 'http://127.0.0.1:3000/project/new' 访问 XMLHttpRequest 来源“http://127.0.0.1:4200”已被 CORS 策略阻止: 对预检请求的响应未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。

我的 SAM 模板:

AWSTemplateFormatVersion: '2010-09-09'
Transform: 'AWS::Serverless-2016-10-31'
Parameters:
   [my parameters]
Globals:  
   Function:
       Runtime: nodejs6.10
       Handler: index.handler
       Timeout: 30
       AutoPublishAlias: live
       DeploymentPreference:
         Type: AllAtOnce
Resources:
  ## ApiGateway
  ApiGatewayRestApi:
    Type: 'AWS::Serverless::Api'
    Properties:
      Name: myAPI
      StageName: !Ref Stage
      Cors: "'*'"
      EndpointConfiguration: REGIONAL
      DefinitionBody:
        swagger: "2.0"
        info:
          version: "1.0"
          title: MyAPI
          host: !Ref Host
        schemes:
          - "https"
        consumes:
          - application/json
        produces:
          - application/json
        paths:
           put:
             responses: {}
             x-amazon-apigateway-integration:
                uri:
                  Fn::Join:
                    - ''
                    - - 'arn:aws:apigateway:'
                      - !Ref AWS::Region
                      - ':lambda:path/2015-03-31/functions/'
                      - !GetAtt CreateNewProjectFunction.Arn
                      - '/invocations'
                passthroughBehavior: "when_no_match"
                httpMethod: "PUT"
                type: "aws_proxy"

   ## Lambda functions
   CreateNewProjectFunction:
       Type: 'AWS::Serverless::Function'
       Properties:
         CodeUri: createNewProject/
         Handler: index.handler
         Runtime: nodejs6.10
         MemorySize: 128
         Timeout: 10
         Role: 'myRole'
         Events:
           CreateNewProject:
             Type: Api
             Properties:
               Path:  /project/{id}
               Method: PUT
               RestApiId: !Ref ApiGatewayRestApi
         Environment:
           Variables:
             tableName: !Ref ProjectsTableName    
Outputs:
  Api:
    Description: 'API Gateway endpoint URL'
    Value: 'https://${ApiGatewayRestApi}.execute-api..../'

我的 Lambda:

exports.handler = (event, context, callback) => {
       var response = {
          "statusCode": 200,
          "headers": { "Access-Control-Allow-Origin": "*" },
          "body": "My lambda is OK"
       };
       return callback(null, response);
    }

PS:我的网址没问题,因为我用邮递员测试过

【问题讨论】:

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


    【解决方案1】:

    好的,我找到了。

    我们必须在 template.yaml 中添加一个 lambda 函数:

    resLambdaLocalCorsStub:
        Type: AWS::Serverless::Function
        Properties:
          Handler: index.handler
          Runtime: nodejs6.10
          FunctionName: corsOptions
          CodeUri: corsOptions/
          Timeout: 30
          Events:
            loginOptions: # This block must be repeated for each endpoint that needs CORS support in SAM Local
              Type: Api
              Properties:
                RestApiId: !Ref ApiGatewayRestApi
                Path: /project/{id}
                Method: OPTIONS
    

    这个在apigateway中

    options:
                    x-amazon-apigateway-integration:
                      type: mock
                      requestTemplates:
                        application/json: '{ "statusCode" : 200 }'
                      httpMethod: OPTIONS
                      responses:
                        default:
                          statusCode: 200
                          responseParameters:
                            method.response.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key'"
                            method.response.header.Access-Control-Allow-Methods: "'DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT'"
                            method.response.header.Access-Control-Allow-Origin:  "'*'"
                          responseTemplates:
                            application/json: '{}'
                    responses:
                      '200':
                        headers:
                          Access-Control-Allow-Headers:
                            type: string
                          Access-Control-Allow-Methods:
                            type: string
                          Access-Control-Allow-Origin:
                            type: string  
    

    最后,创建一个 lambda:

    "use strict";
    
    // ***** This handler is used only in local development, for mocking the OPTIONS responses
    // ***** This enables API Tests to pass CORS tests when running locally
    exports.handler = (event, context, callback) => {
      callback(null, {
        statusCode: 200,
        headers: {
          "Access-Control-Allow-Headers": "Content-Type,X-Amz-Date,Authorization,X-Api-Key",
          "Access-Control-Allow-Methods": "POST, GET, PUT, DELETE",
          "Access-Control-Allow-Origin": "*"
        },
        body: ""
      });
    };
    

    【讨论】:

    • 什么是apigateway?是在 template.yaml 中吗?
    • @EduardoDennis 是的,但是有一个默认隐藏(隐含)的默认设置。如果您需要添加这样的自定义项,您可以手动将其重新添加。
    猜你喜欢
    • 1970-01-01
    • 2017-08-11
    • 2018-05-23
    • 2017-03-12
    • 2021-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多