LoginSignup
6
12

More than 3 years have passed since last update.

Lambda + API GatewayでCORSを有効にしているのにCORSでエラーになる

Posted at

Amazon Pinpoint を使用するために、チュートリアル: E メール設定管理システムの設定をやってみたら、ステップ 6: ウェブフォームを作成してデプロイするで引っかかったので。

API GatewayでCORSは有効になっている

API Gatewayのメソッドレスポンスではこんな感じで設定済みなのに、いざ違うドメインから実行しようとするとブロックされてしまう。
1.PNG

対策:Lambda 関数側でもレスポンスヘッダーを設定する必要がある

チュートリアルの前ステップで作成したLambda関数のコードでは、レスポンスが特に設定されていない。

終了時にレスポンスを設定・返却する必要がある。

  const response = {
    "statusCode": 200,
    "headers": {
        "Content-Type": 'application/json',
        "Access-Control-Allow-Headers": "Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token",
        "Access-Control-Allow-Methods": "POST",
        "Access-Control-Allow-Origin": "*"
    },
    "body": JSON.stringify(event)
  };

  callback(null, response);

"body" の中身はJSON形式であれば空でもいい。設定しなかったりただの文字列だとAPI Gateway側のエラーで返される。

6
12
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
6
12