加载.mjs文件报错 MIME type of "application/octet-stream" 的解决方案

/ 默认分类 / 没有评论 / 287浏览

关于浏览器控制台报错 xxx.mjs 文件 Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "application/octet-stream". Strict MIME type checking is enforced for module scripts per HTML spec.问题的解决方案

第一次遇到这个问题,本地访问没问题,使用Nginx部署好后,但浏览器控制台报错提示: .mjs Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "application/octet-stream". Strict MIME type checking is enforced for module scripts per HTML spec.

原因

由于nginx无法识别mjs文件,从而在http header中错误的使用 Content-Type:application/octet-stream 来传输mjs文件,导致浏览器端认为它不是一个合法的js脚本

解决方案

修改nginx的MIME type文件,修改对应的MIME type与mjs的映射,操作如下:

去nginx配置文件中发现 mimetype文件路径为 /etc/nginx/mime.types

打开mime.types文件

sudo vim /etc/nginx/mime.types

找到如下配置内容

application/javascript                 js;

修改为

application/javascript                 js mjs;

然后重启Nginx

sudo nginx -s reload

再次访问发现网页没有报错,可以正常运行(如还有报错可尝试强刷或清除缓存后再试)