0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ペライチのhtmlファイルから外部APIを叩く

Posted at

やりたいこと

htmlファイルをブラウザで開くだけでAPIコール〜描画するまでの仕組みを構築したい。

サンプルコード

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>任意のタイトル</title>
  </head>
  <body>
    <div id="result">データ取得中...</div>
    <script>
      const proxyUrl = "https://cors-anywhere.herokuapp.com/";
      const apiUrl = "APIのエンドポイント"
      const reqUrl = proxyUrl + apiUrl;
      const options = {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
          "Access-Control-Allow-Origin": "*",
          "X-Requested-With": "XMLHttpRequest",
          "Content-Type": "application/json",
          "Origin": "http://localhost:5500"  // VSCode: Live Serverで起動想定
        },
        mode: "cors"
      };
      fetch(reqUrl, options)
        .then((response) => response.json())
        .then((data) => {
          console.log(data)  // デバッグ用
          // データの表示処理など(div#resultに値を表示する等)
        })
        .catch((error) => console.error(error));
    </script>
  </body>
</html>

ポイント

ローカルサーバ→外部APIに直接通信する際にCORSエラーが発生する。
なので、ローカルサーバ→プロキシサーバ(※)→外部APIのように通信すればCORSエラーを回避できる。
プロキシサーバがローカルからのリクエストを代わりに外部APIに送ってくれている。

https://cors-anywhere.herokuapp.com

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?