前端部署后浏览器报错排查
前端项目部署到服务器后,使用浏览器访问可能遇到如下报错:
bash
Failed to load module script: Expected a JavaScript-or-Wasm module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.
此时可能会认为是 Nginx 配置的问题。是,也不是。
错误原因分析
这个错误的真正原因是服务器上缺少了 index.html 引用的第一个 JS 文件。
那为什么不报 404,而是这么一个奇怪的问题呢?
Nginx 配置说明
大多数前端项目在 Nginx 中的标准配置如下:
nginx
server {
listen 80;
server_name test.test.cn;
client_max_body_size 10m;
location / {
proxy_set_header Host $http_host;
root /data/html/ysh;
try_files $uri $uri/ @router;
index index.html index.htm;
}
location @router {
rewrite ^.*$ /index.html last;
}
}
当浏览器请求一个 JS 文件时,如果该文件不存在,Nginx 会执行 try_files 逻辑。由于 $uri 和 $uri/ 都不匹配,请求会被重定向到 @router 块,最终返回 index.html 的内容(状态码通常为 200)。
浏览器接收到响应后,发现预期的 JS 文件返回的是 HTML 内容(MIME type 为 text/html),根据 HTML 规范强制的 MIME 类型检查,就会抛出上述错误。
解决方案
找了一圈解决上面问题的 Nginx 配置,配置了又配置,最终发现是因为服务器上少了文件。
建议排查步骤:
- 确认本地构建产物目录中是否存在对应的 JS 文件。
- 检查服务器上的部署目录
/data/html/ysh下是否有完整的构建文件。 - 确保构建时的
base或publicPath配置与服务器访问路径一致。
只要补齐缺失的文件,即可恢复正常。

