0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

AWS日記47(API Gateway - CORS)

Last updated at Posted at 2022-09-30

はじめに

今回はREST API リソースの CORS サポートを有効にします
REST API リソースの CORS を有効にするを参考に、POST メソッドリクエストに対する設定を行います

準備

CloudFormation

AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Description: SampleJsonResponse Page

Parameters:
  ApplicationName:
    Type: String
    Default: 'SampleJsonResponsePage'

Resources:
  FrontPageApi:
    Type: AWS::Serverless::Api
    Properties:
      Name: SampleJsonResponsePageApi
      EndpointConfiguration: REGIONAL
      StageName: Prod
  FrontPageFunction:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: SampleJsonResponsePageFunction
      Handler: bootstrap
      Runtime: provided.al2
      Timeout: 5
      CodeUri: target/lambda/sample_json_response/
      MemorySize: 256
      Architectures: ["arm64"]
      Description: 'SampleJsonResponse Function'
      Events:
        testapi:
          Type: Api
          Properties:
            Path: '/api/sample'
            Method: post
            RestApiId: !Ref FrontPageApi

Outputs:
  FunctionName:
    Value: !Ref FrontPageFunction
    Description: Name of the Lambda function
  APIURI:
    Description: "URI"
    Value: !Join ['', ['https://', !Ref FrontPageApi, '.execute-api.', !Ref 'AWS::Region', '.amazonaws.com/', 'Prod/']]

Lambda設定

レスポンスヘッダー追加

    let mut map = HeaderMap::new();
    map.append(header::ACCESS_CONTROL_ALLOW_ORIGIN, "https://www.example.com".parse().unwrap());
    map.append(header::ACCESS_CONTROL_ALLOW_HEADERS, "Content-Type".parse().unwrap());
    map.append(header::ACCESS_CONTROL_ALLOW_METHODS, "POST".parse().unwrap());
    Ok(
        ApiGatewayProxyResponse {
            status_code: 200,
            body: Some(resp_json.to_string().into()),
            is_base64_encoded: None,
            headers: map,
            multi_value_headers: HeaderMap::new()
        }
    )

API Gateway設定

02.jpg

03.jpg

  • POSTメソッドのレスポンスヘッダーを追加する
    • Access-Control-Allow-Headers
    • Access-Control-Allow-Methods
    • Access-Control-Allow-Origin

確認

  • ローカルサーバーからAPIにリクエストする
    07.jpg

Originが異なるためブロックされる

終わりに

Lambda側だけでなく、API Gateway側の設定も必要なので初回は混乱しました。

AWS デベロッパーガイドの他に以下の記事を参考にしました。

API Gateway + Lambda のCORS関連エラーの対策

API Gateway の Lambda プロキシ統合のCORS対応をまとめてみる

追記

AWS Serverless Application Model (AWS SAM) テンプレート に 「Cors」 の設定をすることで、本文の 「API Gateway設定」 を行う必要がなくなります。
参考資料 : CorsConfiguration

      Cors:
        AllowMethods: "'POST'"
        AllowHeaders: "'Content-Type,Origin'"
        AllowOrigin: "'https://www.example.com'"
        MaxAge: "'600'"
        AllowCredentials: true
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?