やりたいこと
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に送ってくれている。