PUT / POST / DELETE: ошибка 403 запрещена + ошибка CORS с AWS SAM - PullRequest
0 голосов
/ 29 октября 2018

Я хочу сделать простой HTTP-запрос, но меня блокируют следующие ошибки:

zone.js: 2969 ВАРИАНТОВ http://127.0.0.1:3000/project/new 403 (ЗАПРЕЩЕНО)

Доступ к XMLHttpRequest по адресу http://127.0.0.1:3000/project/new' из origin '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..../'

Моя лямбда:

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

PS: мой URL в порядке, потому что я проверял его с почтальоном

1 Ответ

0 голосов
/ 29 октября 2018

Хорошо, я нахожу это.

Мы должны добавить лямбда-функцию в template.yaml:

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  

И чтобы закончить, создайте лямбду с:

"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: ""
  });
};
...