Docker部署React-Vite到Azure Web App:base URL加载失败求助
问题解决:React-Vite Docker部署到Azure Web App根路径无法加载,子路由正常
问题现象
- 部署到Azure Web App后,访问根路径(/)时应用无法渲染,Chrome控制台报MIME类型错误(JS模块被返回text/html);
- 直接访问/login、/register等子路由正常;
- IE浏览器访问根路径正常,Chrome异常;
- 本地运行同一Docker镜像时所有功能正常。
报错信息
main.jsx: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. client: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. pwa-entry-point-loaded: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. @react-refresh: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.
解决方案
1. 修正Nginx配置,确保MIME类型正确
本地运行正常但Azure异常,可能是Azure环境下Nginx默认MIME类型配置缺失,需显式引入并优化静态文件处理:
修改nginx.conf为:
include /etc/nginx/mime.types; default_type application/octet-stream; server { listen 80; server_name _; root /usr/share/nginx/html; index index.html; location / { try_files $uri $uri/ /index.html; } # 静态文件直接返回,避免重写触发MIME错误 location ~* \.(js|jsx|css|html|png|svg|ico|txt)$ { expires 1y; add_header Cache-Control "public, immutable"; } error_page 404 /index.html; error_page 500 502 503 504 /50x.html; }
2. 确认Azure Web App容器端口配置
在Azure门户进入你的Web App:
- 导航到「配置」→「常规设置」
- 确保「容器端口」设置为
80(与Nginx监听端口一致) - 保存设置并重启Web App
3. 验证生产构建无开发代码
检查本地生产构建的dist/index.html,确认是否包含@react-refresh相关脚本:
- 执行
npm run build --mode production - 打开
dist/index.html,如果发现开发环境的脚本,检查:package.json中build命令是否为"build": "vite build"vite.config.js中VitePWA的devOptions.enabled是否仅在开发模式开启(你的配置已正确设置)
4. 清除缓存
- Chrome浏览器强制刷新:
Ctrl+Shift+R,或清空浏览器缓存后重试 - 若Azure Web App启用了CDN,进入CDN资源管理页面清除缓存
5. 检查Azure容器日志排查文件缺失
在Azure门户进入Web App→「日志流」,查看Nginx访问日志:
- 搜索
main.jsx等资源的请求记录,若返回404,说明容器内dist文件未正确复制 - 可通过Azure CLI进入容器查看文件:
az webapp ssh --name <你的WebApp名> --resource-group <资源组名>,然后执行ls /usr/share/nginx/html确认文件存在
补充说明
本地运行正常是因为本地Nginx环境的MIME配置完整,而Azure容器环境可能存在默认配置差异;IE正常是因为其MIME类型检查规则较宽松,Chrome严格遵循HTML规范导致报错。
内容的提问来源于stack exchange,提问作者Adnan Ali
相关产品推荐
相关产品推荐

