LoginSignup
64
54

More than 5 years have passed since last update.

jQueryからAmazon API Gatewayを使用する

Last updated at Posted at 2015-07-31

概要

AWSから新サービス API Gateway がリリースされました。Lambda (あるいは外部のHTTP) と連携させることで、他のAWSシステムやバックエンドシステムが提供する機能をREST APIとして公開することが可能となります。

Gateway APIを使った最も分かりやすい例は、下のフローのようにLamdaファンクション (Node.jsやJava) を介してバックエンドのDBからデータを取得したり更新する構成かと思います。

EC2 <-(HTTP)-> API Gateway <-> Lambda <-> DB (RDS, DynamoDB...)

ここでは手始めに、jQuery経由でAPI Gatewayをコールする方法について説明します。

※2015年8月1日時点、Gateway APIのTokyoリージョンは提供されていません。ただしリージョンブリッジが可能なため、Lambda以降のシステムをTokyoリージョンで構築することは可能です。

実装

jQuery側はいつも通り$.ajax()をコールするだけ。urlにはAPI Gatewayから発行されたURLを指定します。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
  (function() {
    var data = {
      'id': 'xxx'
    }

    $.ajax({
      type: 'POST',
      url: '{ENDPOINT_URL}',
      data: JSON.stringify(data),
      success: function(data) {
        console.log(data);
      }
    });
  })();
</script>

ただしこの状態でリクエストを送信すると、CORSの制限に引っかかり、API GatewayからNo 'Access-Control-Allow-Origin' header is present on the requested resource.といったエラーが返されます。

error_response.png

この問題を回避するには、API Gateway側でCORSを有効化する必要があります。
詳細は Enable CORS for a Method in API Gateway に記載されてますが、基本的には対象リソースの"Method Response"、"Integration Response"を編集するだけです。

Method Responseの設定

method_response.png

Integration Responseの設定

integration_response.png

"Integration Response"の"Mapping value"では、シングルクォートを値に含める必要がある点に注意して下さい。

最後に"Deploy API"を実行してデプロイすれば問題は解決します。

success_response.png

ここでは console.log(data) の結果として、API Gatewayのバックエンドで実行されているLambdaファンクションの戻り値が表示されています。

64
54
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
64
54