1

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

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

从源“ http://127.0.0.1:4200 ”访问位于“ http://127.0.0.1:3000/project/new ”的 XMLHttpRequest已被 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..../'

我的拉姆达:

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

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

4

1 回答 1

0

好的,我找到了。

我们必须在 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: ""
  });
};
于 2018-10-29T09:41:48.867 回答