前端项目部署到服务器后,使用浏览器访问可能遇到如下报错:
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 的配置中包含了 try_files 和 location @router 规则。当请求的 JS 文件不存在时,Nginx 不会返回 404,而是通过重写规则返回 index.html 的内容。
浏览器请求 JS 文件,却收到了 HTML 内容,导致 MIME 类型检查失败,从而报出上述错误。
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;
}
}
上述配置是大多数前端项目的标准 SPA 路由配置。
总结:排查此类问题不能仅局限于 Nginx 配置,需确认服务器上是否存在对应的静态资源文件。

