1
0

Refused to execute script from '(URL)' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.エラー対応

Last updated at Posted at 2024-03-17

前書き

開発中に下記のエラーに遭遇したので、その対処法の備忘録です。

エラー文

Refused to execute script from  'http://localhost:8080/2ndPage/app.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
create:7 
Refused to apply style from 'http://localhost:8080/2ndPage/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

原因

このエラーが意味するところは
「ブラウザが'http://localhost:8080/2ndPage/app.js'からリソースを取得しようとしているけど、MINEタイプが違うよ!」
って感じです。

今回の場合、実はMINEタイプの問題ではなく、URLに問題がありました。

MIMEタイプとは? サクっと一言で説明すると、ファイルの種類を表す情報、が「MIMEタイプ」

開発中のWebアプリのページ構成は

Page1
Page2
Page3
└2ndPage

といったようになっており、2ndPageへのアクセスの際にはPage3から遷移する必要があります。
2ndPageのリソースを取得したい場合、何の設定もしていないとリソースを取得する場所がおかしくなってしまう場合があります。

今回の例で説明します。
Reactでのリソースの取得は基本的に、ルートディレクトリのapp.jsから行いますが、エラー文を確認するとhttp://localhost:8080/2ndPage/app.jsからリソースを取得しようとしてしまっていることがわかります。

そのため、正しいURLからリソースを取得するように修正する必要があります。

対処法

対処は至って簡単です。

webpack.common.jsなどの設定ファイルのoutputpublicPath:"/";を設定するだけです。

この設定追加によって、リソースの取得は常にルートディレクトリから行われるようになるため、常にapp.jsからのリソース取得が行われるようになります。

具体的にはこんな感じ。

webpack.js
output:{
 path:path.resolve(__demame,"dist"),
 publicPath:"/",
}
1
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
1
0