【问题标题】:Reloading returns Cannot GET error on MEAN Stack (Angular 6, Express)重新加载在 MEAN Stack (Angular 6, Express) 上返回无法获取错误
【发布时间】:2018-11-09 17:27:10
【问题描述】:

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

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

如何解决?

【问题讨论】:

标签: angular express mean-stack


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2018-12-03
    • 2016-02-25
    • 2018-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-06
    • 1970-01-01
    • 2017-02-13
    相关资源
    最近更新 更多