実現
JavaScriptで、jsonファイルを読み込み、それをHTMLのtextContentに反映させたい。
前提
JavaScript練習中です。index.html、script.js、text.json、という3つのファイルを同一フォルダに保存しています。
この、scriptの中で、「text.json」から情報を取得し、「index.html」へ反映させたいのですがエラーが出ます。
発生している問題・エラーメッセージ
①Access to fetch at 'file:///C:/Users/** 具体的なファイルの位置 **/text.json' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, isolated-app, chrome-extension, chrome, https, chrome-untrusted.
②GET file:///C:/Users/okamo/Desktop/Taro/Programming/JavaScript/0508/text.json net::ERR_FAILED (anonymous) @ script.js:4
③Uncaught (in promise) TypeError: Failed to fetch at script.js:4:1
該当のソースコード
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div class="result">初期値</div> <script src="script.js"></script> </body> </html>JS
const result = document.querySelector(".result");
const url = "text.json";
fetch(url).then
(function(response) {
return response.json();
}).then
(function (json) {
result.textContent = json.text;
});
JSON
{
"name": "Taro"
}
試したこと
グーグルで解決策を探しましたが見つかりませんでした。
補足情報(FW/ツールのバージョンなど)
エディタはVSCodeを使っています。
回答2件
あなたの回答
tips
プレビュー