LoginSignup
5
6

More than 3 years have passed since last update.

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

Posted at

概要

「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());

参考

リクエスト結果の確認

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

error対処

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

image.png

# エラー文
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で問い合わせるぞ( *˙︶˙*)وグッ!

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