どうもこんにちは。
今回は、サーバを立てずにHTMLで同じディレクトリにあるJSONを読み込むのに苦戦したので、その方法をメモとして残します。
とりあえずHTMLで雛形作る
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Sample</title>
</head>
<body>
<div class="box">
<div class="display-area">
<div>
名前: <span id="name-area"></span>
</div>
<div>
年齢: <span id="age-area"></span>
</div>
</div>
</div>
<script>
const source_src = 'sample_data.json';
var xhr = new XMLHttpRequest();
xhr.open('GET', source_src, false);
xhr.send(null); // ココ!!
if (xhr.status === 200) {
var data = JSON.parse(xhr.responseText);
var nameAreaElement = document.querySelector('.name-area');
var ageAreaElement = document.querySelector('.age-area');
nameAreaElement.textContent = data["datas"]["name"];
ageAreaElement.textContent = data["datas"]["age"];
}
</script>
</body>
</html>
サンプルJSON
sample_data.json
"datas": {
"name": "テスト太郎",
"age": 30
}
さてさて...
作成したindex.html
のファイルパスをコピーしてブラウザで開くと...
Access to XMLHttpRequest at 'file:///Users/testuser01/sample.json' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, isolated-app, brave, https, chrome-untrusted, data, chrome-extension, chrome.
CORS制約に反していると言われてしまいます。
解決するには
以下のコマンドをターミナルで実行します。
# windowsの場合
chrome.exe --disable-web-security --user-data-dir="C:/ChromeDevSession"
# macの場合
open -na "Google Chrome" --args --disable-web-security --user-data-dir="$HOME/ChromeDevSession"
必ず、Chromeを完全に終了した状態で実行してください。
バックグラウンドで動いている状態では実行できないので、注意してください。
これでJSONファイルを読み込むことができるようになります。