Angular子目录部署报错:模块脚本MIME类型不符问题排查
部署Angular应用后MIME类型报错排查问题
部署Angular应用后遇到报错:
Failed to load module script: Expected a JavaScript 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.
该应用在安装Nx前运行正常,目前正尝试移除Nx。已排除base-href配置问题:
- package.json中已配置带
base-href的构建命令 - 构建后index.html已正确生成
<base href="/app_name/angular/">
package.json的scripts配置
"scripts": { "ng": "ng", "start": "ng serve", "prebuild": "npm --no-git-tag-version version patch", "build": "ng build", "prebuild-local": "npm --no-git-tag-version version patch", "build-local": "ng build --configuration=local --base-href=/app_name/angular/", "build-prod": "ng build --configuration=prod --base-href=/AppName/angular/", "build-test": "ng build --configuration=testing --base-href=/AppName/angular/", "watch": "ng build --watch --configuration development", "test": "ng test" },
当前部署操作
通过npm run build-local生成分发文件,部署到Apache Tomcat的http://localhost:8080/app_name/angular/路径下,并已添加Tomcat重写规则:RewriteRule ^/app_name/angular/(.*) /app_name/angular/index.html
后续排查方向
- 检查Tomcat MIME类型配置:确认Tomcat的
conf/web.xml中是否存在JavaScript文件的正确MIME映射,需包含<mime-mapping><extension>js</extension><mime-type>application/javascript</mime-type></mime-mapping>,缺失或错误会导致静态资源返回text/html类型。 - 调整重写规则范围:当前规则会匹配所有请求(包括JS/CSS等静态资源),导致静态资源被转发到index.html从而返回text/html。需修改规则排除静态资源,比如:
RewriteRule ^/app_name/angular/(?!.*\.(js|css|png|jpg|svg)$)(.*) /app_name/angular/index.html,确保仅路由请求被重定向。 - 验证构建产物资源路径:检查dist目录下index.html中引用的JS/CSS资源路径是否以
/app_name/angular/开头,避免相对路径导致请求404后被重写规则转发。 - 清理Nx残留配置:排查项目中是否还有Nx相关配置文件(如nx.json、angular.json中的Nx插件配置),残留配置可能影响构建产物的资源引用逻辑。
- 检查Tomcat上下文配置:确认Tomcat中
app_name应用的上下文配置是否存在大小写问题(比如配置中的AppName和实际部署路径app_name不一致),导致资源请求路径不匹配。 - 查看浏览器请求详情:打开开发者工具,查看报错JS模块的请求URL和响应头,确认资源是否存在、响应的Content-Type是否为text/html,定位是资源不存在被重定向还是MIME类型配置错误。
内容的提问来源于stack exchange,提问作者camaleongdl
相关产品推荐
相关产品推荐

