LoginSignup
0
0

JavaScriptでfetch()メソッドが使えない

Posted at

はじめに

VSCodeでfetch()メソッドを使おうとしたところうまく実行できなかったため、原因と対策をまとめます。

エラー内容

以下のようなソースコードでjsonファイルを読み込もうとしたらエラーが発生しました

main.js
async function foo() { 
  const jsonData = await fetch('./foo.json');
  return await jsonData.json();
} 
エラー内容
Access to fetch at 'xxxxxx 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.
prefectures.json:1 
Failed to load resource: net::ERR_FAILED
main.js:2 

原因

fetch()メソッドがローカルファイルシステムから直接ファイルを読み込むことを許可していないため。

対策

以下の通りVSCodeの拡張機能でローカルサーバを立ち上げて実行する。

VSCodeの拡張機能でLive Serverをインストールする
image.png

開きたいhtmlファイルを右クリック→Open with Live Serverをクリック
image.png

これによりHTTP(S)プロトコルを介したリソースの取得が可能になり、fetch()メソッドが使えるようになります。

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