重新加载 returns 无法在 MEAN 堆栈上获取错误(Angular 6,Express)

Reloading returns Cannot GET error on MEAN Stack (Angular 6, Express)

我在 MEAN 堆栈应用程序上遇到路由问题。通过 Angular 开发服务器(使用 ng serve 然后在 localhost:4200 上查看)测试站点时,我的路由正常工作。但是,当我尝试仅使用我为后端构建的 Express 服务器时,我 运行 遇到了一些问题。问题在于,尽管该站点运行良好,但即使在 运行ning ng build 之后路由到所有静态页面,当从地址栏而不是页面上的链接重新加载或导航到页面时, 我遇到了

"Cannot GET" error.

路由在 Angular 生成的文件夹中的 app.module.ts 文件中定义。它看起来像这样:

const appRoutes: Routes = [
  {path: '', component: HomeComponent, canActivate: [AuthGuard]}, // accessible to all
  {path: 'register', component: RegisterComponent, canActivate: [AuthGuard]}, // accessible to all
  {path: 'login', component: LoginComponent, canActivate: [AuthGuard]}, // accessible to all
  {path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard, UserAuthGuard]}, // only accessible by users
  {path: 'ridequeue', component: RidequeueComponent, canActivate: [AuthGuard, VolunteerAuthGuard]}, // Volunteers and Administrators only
  {path: 'viewusers', component: ViewusersComponent, canActivate: [AuthGuard, VolunteerAuthGuard]}, // Volunteers and Administrators only
  {path: 'manageusers', component: ManageusersComponent, canActivate: [AuthGuard, AdministratorAuthGuard]}, // Administrators only
  {path: 'adminpanel', component: AdminpanelComponent, canActivate: [AuthGuard, AdministratorAuthGuard]}, // Administrators only
  {path: 'profile', component: ProfileComponent, canActivate: [AuthGuard, UserAuthGuard]}, // only accessible by users
  {path: 'feedback', component: FeedbackComponent, canActivate: [AuthGuard, UserAuthGuard]}, // only accessible by users
  {path: 'unauthorized', component: UnauthorizedComponent, canActivate: [AuthGuard]} // accessible to all
];

它是在导入列表中使用 RouterModule.forRoot(appRoutes) 在此文件中实现的。

至于 Express 应用程序内的路由,我为访问的不同 API 配置了路由,并指导静态站点的去向(通过 Angular 创建的前端,我有:

app.use(express.static(path.join(__dirname, 'public')));

其他可能相关的信息:我正在使用 Express 4.16 和 CORS 中间件,Angular 6 和 Chrome 来测试它。

如何解决?

此问题的解决方法是将中间件添加到我的 Express 应用程序以确保启用后备 - 在没有文件可提供时导航到 index.html。我最终都尝试了 express-history-api-fallback and connect-history-api-fallback。经过一些配置后,两者都解决了问题,但我坚持使用 Express,因为它是专门为 Express 构建的。