javascript エラー「Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of “application/json”. Strict MIME type checking is enforced for module scripts per HTML spec.」の解決方法
- 作成日 2022.08.09
- javascript
- javascript
javascriptで、エラー「Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of “application/json”. Strict MIME type checking is enforced for module scripts per HTML spec.」が発生した場合の原因と解決方法を記述してます。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 104.0.5112.81
エラー内容
以下の、「json」ファイルを読み込むコードを実行した際に発生。
<script type="module" src="test.js"></script>
「test.js」
import test from './test.json' assert {type: 'json'};
for (let item in test) {
console.log(item);
};
エラーメッセージ
Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "application/json". Strict MIME type checking is enforced for module scripts per HTML spec.
画像
firefox102の場合は、以下のエラーが発生します。
MIME タイプ (“application/json”) が許可されていないため、“http://mebee.com:8080/test.json” からのモジュールの読み込みがブロックされました
画像
原因
「json」ファイルを「import」文で読み込むには「assert {type: ‘json’}」を指定する必要があるため
解決方法
「assert {type: ‘json’}」を使用する
import test from './test.json' assert {type: 'json'};
for (let item in test) {
console.log(item);
};
ただし、firefox102では、別のエラーになり使用できません。
Uncaught SyntaxError: import assertions are not currently supported
safari15.5でもエラーとなります。
SyntaxError: Unexpected identifier 'assert'. Expected a ';' following a targeted import declaration.
-
前の記事
PostgreSQL 時間から日数を計算する 2022.08.09
-
次の記事
Rust 数値の符号を判定する 2022.08.09
コメントを書く