You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GCP Cloud Run部署Angular应用:直接访问路由遇MIME类型错误

问题:Angular应用部署GCP Cloud Run(Nginx容器)直接访问路由报MIME类型错误

现象

将Angular应用以Nginx容器形式部署在GCP Cloud Run上,从首页加载并站内导航正常,但直接访问应用内路由时失败,控制台报错:

runtime.46fb68c434174d9b.js:1 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.
polyfills.938d3d63ac22b057.js:1 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.
main.89919748d2009153.js:1 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

已配置nginx.conf引入mime.types,并添加路由重写规则:

location / {
  try_files $uri $uri/ /index.html;
  index index.html index.htm Default.htm;
  add_header Strict-Transport-Security "max-age=31536000; includeSubDomains";
  add_header X-Content-Type-Options nosniff;
}

解决方案

1. 确认mime.types正确引入

在nginx.conf的http块内必须正确引入官方mime类型配置,否则Nginx无法识别JS文件的MIME类型:

http {
  include       /etc/nginx/mime.types;
  default_type  application/octet-stream;

  # 其他配置项...
}

如果自定义了mime.types文件,确保包含JS类型的定义:

application/javascript          js mjs;

2. 拆分静态资源与SPA路由规则

当前的location /会把所有请求(包括JS/CSS等静态资源)都尝试重定向到index.html,直接访问路由时,Nginx会把JS文件的请求路径误判为路由,返回index.html而非实际JS文件。修改配置如下:

# 优先匹配静态资源,直接返回文件
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf)$ {
  root /usr/share/nginx/html;
  expires 1y;
  add_header Cache-Control "public, immutable";
}

# 处理SPA路由,非静态资源请求重定向到index.html
location / {
  try_files $uri $uri/ /index.html;
  index index.html index.htm;
  add_header Strict-Transport-Security "max-age=31536000; includeSubDomains";
  add_header X-Content-Type-Options nosniff;
}

3. 检查Angular打包配置

执行打包命令时,确保指定正确的基础路径(如果应用部署在根路径则用/):

ng build --prod --base-href /

若部署在子路径,替换/为实际路径,比如/my-app/。

4. 验证Docker构建流程

确保Dockerfile正确复制打包产物和Nginx配置:

FROM nginx:alpine
# 替换成你的Angular应用打包后的目录
COPY dist/your-app /usr/share/nginx/html
# 复制自定义nginx配置
COPY nginx.conf /etc/nginx/nginx.conf

启动容器时确认Nginx加载的是你自定义的配置文件,而非默认配置。


内容的提问来源于stack exchange,提问作者Harry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 21:33:25