Angular 14 PWA路由失效:页面刷新出现404错误
解决Nx Monorepo Angular 14 PWA刷新路由404问题
核心原因
单页应用(SPA)的路由属于客户端路由,刷新页面时浏览器会直接向服务器请求对应路径(比如/login),但服务器上不存在该路径的物理文件,因此返回404。添加PWA后需要确保服务器与Angular Service Worker配合,将所有路由请求 fallback 到index.html。
解决方案
1. 配置Nx开发服务器
在应用的project.json文件中,找到targets.serve.options,添加historyApiFallback: true,让Webpack Dev Server自动将所有路由请求转发到index.html:
{ "targets": { "serve": { "options": { "historyApiFallback": true, // 保留原有其他配置 } } } }
2. 修正ngsw-config.json的index路径
当前配置中index指向源码路径src/index.html,构建后需使用相对于输出目录的路径,修改为:
{ "index": "index.html", // 保留原有其他配置 }
3. 生产服务器路由 fallback 配置
部署到生产环境时,需根据服务器类型配置路由重定向:
- Nginx:在配置文件中添加:
location / { try_files $uri $uri/ /index.html; } - Apache:创建/修改
.htaccess文件:RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L] - Node.js(Express):使用
connect-history-api-fallback中间件:const express = require('express'); const history = require('connect-history-api-fallback'); const app = express(); app.use(history()); app.use(express.static('dist/apps/your-app-name')); app.listen(3000);
4. 验证基础路由配置
你的AppRoutingModule配置本身无问题,若应用部署在子路径下,需在index.html中设置<base href="/your-subpath/">,并同步manifest.webmanifest的scope和start_url。
验证步骤
- 重启Nx开发服务器:
nx serve your-app-name - 导航到
/login并刷新页面,确认不再出现404 - 构建生产版本:
nx build your-app-name --prod,部署到测试服务器验证生产环境行为
内容的提问来源于stack exchange,提问作者Motassem Jalal
相关产品推荐
相关产品推荐

