Angular 19部署GitHub Pages遇JSON 404及路由刷新失效问题
1. 刷新页面路由失效显示404的修复
Angular是单页应用(SPA),GitHub Pages作为静态托管服务,刷新页面时会直接请求对应路由的物理文件,但这类文件实际不存在,因此触发404。提供两种常用解决方案:
方案一:启用Hash路由
修改app-routing.module.ts,配置HashLocationStrategy:
import { NgModule } from '@angular/core'; import { RouterModule, Routes, HashLocationStrategy, LocationStrategy } from '@angular/router'; const routes: Routes = [ // 你的现有路由配置 ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], providers: [{ provide: LocationStrategy, useClass: HashLocationStrategy }] // 添加该配置项 }) export class AppRoutingModule { }
配置后路由会变为https://francislainy.github.io/bible-quiz/#/xxx格式,刷新时不会触发GitHub Pages的404逻辑。
方案二:通过404.html实现路由重定向
若不想使用Hash路由,可在docs目录下创建404.html,内容与index.html完全一致。然后在index.html的<head>标签内添加以下脚本:
<script> (function(l) { if (l.search) { const q = {}; l.search.slice(1).split('&').forEach(function(v) { const a = v.split('='); q[a[0]] = a.slice(1).join('=').replace(/~and~/g, '&'); }); if (q.p !== undefined) { window.history.replaceState(null, null, l.pathname.slice(0, -1) + (q.p || '') + (q.q ? '?' + q.q : '') + l.hash); } } }(window.location)) </script>
这种方式可保持干净的路由格式,但需确保每次build后404.html被正确放置在docs目录中。
2. Services文件夹中JSON文件请求404的修复
该问题通常是打包时未将JSON文件纳入输出目录,或请求路径错误导致:
步骤1:检查angular.json的assets配置
打开angular.json,找到projects -> bible-quiz -> architect -> build -> options -> assets,确保src/services被包含在数组内:
"assets": [ "src/favicon.ico", "src/assets", "src/services" // 添加此项,确保services文件夹被打包到输出目录 ]
步骤2:使用相对路径请求JSON文件
在服务代码中,请求JSON时避免使用绝对路径(如/services/data.json),改用相对路径(如./services/data.json或services/data.json),确保路径相对于当前页面正确。
步骤3:验证打包后的文件结构
执行npm run build后,检查docs目录下是否存在services文件夹及对应的JSON文件。若不存在,重新核对assets配置,或临时手动复制services文件夹到docs目录(建议优先通过配置实现自动打包)。
额外部署注意事项
- 每次build后,确认
docs目录为最新打包产物,移除browser文件夹后再推送至主分支。 - 检查GitHub Pages设置,确认部署来源为主分支的
/docs文件夹(仓库Settings -> Pages -> Build and deployment路径下配置)。
内容的提问来源于stack exchange,提问作者Francislainy Campos

