Angular应用部署在Ingress Controller后出现MIME类型错误求助
问题分析与解决方案
核心问题
出现Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html"错误的根源有两点:
- Ingress配置中错误的
rewrite-target注解导致静态资源路径解析异常,Nginx返回HTML页面而非预期的JS模块 - 容器内默认Nginx未适配Angular前端路由,刷新或直接访问子路由时会返回404页面,被浏览器误判为JS模块
解决方案
1. 修正Ingress配置
删除无效的rewrite-target注解(当前路径为根路径/,无需重写规则),修改后的Ingress配置如下:
apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: example-ingress annotations: nginx.ingress.kubernetes.io/enable-cors: "true" nginx.ingress.kubernetes.io/cors-allow-origin: "http://localhost:4200" nginx.ingress.kubernetes.io/cors-allow-methods: "PUT, GET, POST, DELETE, OPTIONS" nginx.ingress.kubernetes.io/cors-allow-headers: "Authorization, Content-Type" spec: ingressClassName: nginx rules: - host: hostname.local http: paths: - path: / pathType: Prefix backend: service: name: web-spa-service port: number: 80
2. 配置容器内Nginx支持Angular路由
默认Nginx镜像无法处理Angular前端路由,需自定义Nginx配置,确保所有路由请求都返回index.html。
操作步骤:
- 在项目根目录创建
nginx.conf文件,内容如下:
events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; server { listen 80; root /usr/share/nginx/html; index index.html; # 适配Angular前端路由 location / { try_files $uri $uri/ /index.html; } } }
- 修改Dockerfile,将自定义配置复制到容器中:
# Stage 1: Build the Angular application FROM node:18 AS build WORKDIR /app COPY src/WebSPA/package*.json ./ RUN npm install COPY src/WebSPA ./ RUN npm run build --prod # Stage 2: Serve the Angular application FROM nginx:alpine # 复制自定义Nginx配置 COPY nginx.conf /etc/nginx/nginx.conf COPY --from=build /app/dist/web-spa/browser /usr/share/nginx/html EXPOSE 80 CMD ["nginx", "-g", "daemon off;"]
3. 重新构建并部署
更新镜像版本后重新部署资源:
# 构建新镜像 docker build -t phadkesharanmatrixcomsec/iva-workflow:web-spa-2.1 . # 推送镜像(若需) docker push phadkesharanmatrixcomsec/iva-workflow:web-spa-2.1 # 更新Deployment kubectl set image deployment/web-spa-deployment web-spa=phadkesharanmatrixcomsec/iva-workflow:web-spa-2.1
验证
部署完成后访问http://hostname.local,刷新页面或直接访问Angular子路由,确认控制台无MIME类型错误,应用正常运行。
内容的提问来源于stack exchange,提问作者Sharan Phadke
相关产品推荐
相关产品推荐

