[Javascript] API Gateway に対して fetch メソッドでリクエストする


概要

「javascript から API Gateway にリクエストできるかどうか、とりあえず試したい」
そんなときは、ブラウザのコンソールを使うとラクチン(^ワ^*)

...というわけで、ブラウザに javascript の fetch メソッドを打ち込んでリクエストすることにするぞ!

今回はその方法のメモ

環境

API Gateway は API Key でアクセス制御を行っているものとする。

参考

ソース

ブラウザコンソールに打ち込むソース

fetch('API GatewayのURL', {headers: {"x-api-key": "API key をここに打つ"}}).then(response => response.json());

// sample
fetch('https://hogehoge12345.execute-api.us-east-2.amazonaws.com/xxxxxxx/sample', {headers: {"x-api-key": "abcdefghijklmnopqrstuvwxyz"}}).then(response => response.json());

// もしアクセス制御を一切行っていないのであれば、'headers': {} なしでよい
fetch('https://hogehoge12345.execute-api.us-east-2.amazonaws.com/xxxxxxx/sample').then(response => response.json());

参考

リクエスト結果の確認

  • ここをクリックすると確認できる
  • 中身

error対処

コンソールにこんなエラーが出ることがある

# エラー文
Access to fetch at 'https://url' from origin 'https://hoge' has been blocked by CORS policy:
  No 'Access-Control-Allow-Origin' header is present on the requested resource.

If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

これは API Gateway の "CORS有効化" という作業を行えば回避できる
※ただし、URLやAPI Keyが間違っているときもなぜかこのエラーが出た...なぜだ

参考

おわりに

ネットの海の情報だけでなんとかAPI Gatewayへのリクエストが行えました。
今度はReactで問い合わせるぞ( *˙︶˙*)وグッ!