LoginSignup
2
5

More than 3 years have passed since last update.

API Gateway 経由で Lambda 呼び出して CORS ではまったのでメモ。

Last updated at Posted at 2019-12-06

概要

Vue.js から API Gateway 経由で Lambda 関数を呼び出したら CORS のエラーが出てはまったので書きます。状況としては、Vue.js で axios の get を使用して、認証ありの API Gateway 経由で Lambda 関数を呼び出したら、console に "Access to XMLHttpRequest at '< API の URL >' from origin '< フロントの URL >' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource." というエラーが出ました。ちなみに、API Gateway で CORS の有効化は既に行なっている状況でした。

CORS を有効化

念のため、CORS を有効化するところから書きます。詳しい方法は AWS 公式ドキュメントの こちらのページ の 「API Gateway コンソールを使用してリソースで CORS を有効にする」 に載っています。
 まず、「アクション」 から 「CORSの有効化」 をクリックします。
image.png
次の画面で、「CORS を有効にして既存の CORS ヘッダーを置換」 ボタンをクリックします。その次の画面で、「既存の値を置き換えます」 ボタンをクリックします。すると CORS が有効化されます。

エラー時の状況と解決方法

エラー発生時は、Lambda 関数を以下のように書いていました。

sample.py
...省略
def lambda_handler(event, context):
    table = dynamoDb.Table(<テーブル名>)
    # DynamoDB からデータを取得 
    response = table.query(
        KeyConditionExpression=Key('<key>').eq('<条件>')
    )
    return response

以下のように、テーブルから取得した値を json.dumps() を使用して JSON 形式に変換し、headers として Access-Control-Allow-Origin に '*' を指定して返すようにすると上手くいきました。

sample.py
...省略
def lambda_handler(event, context):
    table = dynamoDb.Table(<テーブル名>)
    data = table.query(
        KeyConditionExpression=Key('<key>').eq('<条件>')
    )
    response = {
        'statusCode': 200,
        'body': json.dumps(data),
        'headers': {'Access-Control-Allow-Origin': '*'}
    }
    return response
2
5
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
2
5