加载js/mjs模块时服务器返回的 MIME 类型不对导致模块被拒绝执行
浏览器报错
Failed to load module script: The server responded with a non-JavaScript MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.Understand this errorAI
核心问题
浏览器加载模块脚本(如
.mjs
或动态导入的.js
文件)时,服务器返回的 MIME 类型为text/html 或 application/octet-stream
时(而非预期的application/javascript
),导致模块脚本被拒绝执行;
解决方法
修改 nginx 配置文件 nginx.conf
http {
include mime.types; # 引入默认 MIME 类型定义
default_type application/octet-stream; # 未匹配时的默认类型
# 补充或覆盖 MIME 类型
types {
application/javascript mjs; # 新增 .mjs 支持
}
server {
listen 80;
server_name example.com;
root /var/www/html;
# 强制 JS/MJS 文件的 Content-Type
location ~* \.(js|mjs)$ {
add_header Content-Type application/javascript; # 防止类型被覆盖
try_files $uri $uri/ =404;
}
location ~* \.(js|mjs|css)$ {
expires 12h;
access_log off;
}
# 其他配置保持不变...
}
}