重新加载返回 无法在 MEAN 堆栈(角度 6,快速)上获取错误



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

"无法获取"错误。

路由在 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')));

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

如何解决?

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

最新更新