0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

誤ったMIME type設定が原因で、JavaScriptが実行されなかった時の解決方法

Last updated at Posted at 2021-03-13

『体系的に学ぶ-安全なWebアプリケーションの作り方-第2版-』で学んだことを基に、
ログイン機能のサンプル作成中につまづきました。

あるJavaScriptライブラリの利用を試みましたが、
ブラウザ(safari)上で、以下のエラーが発生し、JavaScriptが起動しませんでした。

console(safari)
[Error] Refused to execute http://「ファイル名」.js as script 
because "X-Content-Type-Options: nosniff" was given and 
its Content-Type is not a script MIME type.

今回は、このエラーを解消した方法を投稿します。

開発環境

  • Mac OS(safari)
  • docker-compose

使用しているimage
PHP:7.3-apache
mysql:5.7

解決方法

apacheの設定を変更する。以下の設定を追加しました。

apacheの構成を設定するファイル
AddType text/javascript .js

<Directory "設定を適用させたいディレクトリ">
<Files "設定を適用させたいディレクトリ/*.js">
Header set Content-Type application/javascript; charset=utf-8
</Files>
</Directory>

エラーの原因

apache全体を対象とした設定に、
Header set Context-Type text/html; charset=utf-8
を記述していたので、Javascriptを読み込む際のレスポンスヘッダーが、
Content-Type: text/html; charset=utf-8
となっていたことが原因のようです。

このため、apacheで設定していた
Header always set X-Content-Type-Options nosniffによって、
レスポンスヘッダー Content-Type: text/html; charset=utf-8通りに、
MIME typeをtext/htmlとして、JavaScriptファイルを処理した為に、
エラーが発生したようです。

参考文献

apache official セクションの設定

追記(2021(R.3).03.17(水))

HTTP Response Header(Content-Type)の設定は、
サーバー(Apache)の構成ファイルではなく、
スクリプトファイルで個別に設定しようと思います。
今回の場合であれば、PHPのheader() functionを利用した方が良いと感じました。

ただし、これがセキュリティ的に良いのかはわかりませんので、調べて行きたいです。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?