【问题标题】:What's the right way to set routing for angular2 with koajs用koajs为angular2设置路由的正确方法是什么
【发布时间】:2016-08-23 08:35:37
【问题描述】:

我是 angular2 和 koajs 的新手。也许这是一个愚蠢的问题。

我有一个 angular2 应用程序,其路由表如下:

const appRoutes: Routes = [
  {
    path: 'pats/report/settings',
    component: PatsReportSettingsComponent
  },
  {
    path: 'pats/report/:id',
    component: PatsReportComponent,
    pathMatch: 'full'
  },
  {
    path: 'pats/report/login',
    component: PatsLoginComponent,
    pathMatch: 'full'
  },
  {
    path: '.',
    redirectTo: 'pats/report/login',
    pathMatch: 'full'
  },      
  {
    path: '**',
    component: Pats404PageComponent,
    pathMatch: 'full'
  },
];

如果用户通过根 url (http://localhost:3000) 访问我们的应用程序,然后导航到子页面(例如:http://localhost:3000/pats/report/settings),一切都很好,因为 angular2 应用程序将在内部处理子页面导航并且不会发出对后端的 http 请求。

但是如果用户直接使用子页面 url 访问我们的应用程序,例如:http://localhost:3000/pats/report/settings,则后端 koajs 应用程序将响应 404 状态,因为它在后端不存在路径“pats/report/settings”的路由。

解决此问题的正确方法是什么?

是否应该在后端路由器中为所有客户端子页面路径添加路由并使用 index.html 进行响应?

【问题讨论】:

    标签: angular angular2-routing koa koa-router


    【解决方案1】:

    我不知道 Koajs,但你需要一些中间件。您的后端需要将这些请求重定向到 localhost:3000/,但让 URL 保持原样,这样 Angular 就可以发挥它的魔力!

    查看 koajs 的附加包:

    另一个选项:使用 Hashbang-URLs ! Angular2 URL-Styles

    【讨论】:

    • 查了Angular2 URL-Styles,貌似不推荐Hashbang-URL。
    • 是的,也只是想向您展示该选项。最佳实践是通过您的 koajs-backend 正确处理 unknown URLs
    • 我试过koa-repath,效果很好!再次感谢@mxii
    猜你喜欢
    • 2015-07-29
    • 1970-01-01
    • 1970-01-01
    • 2015-02-10
    • 1970-01-01
    • 1970-01-01
    • 2022-06-28
    • 2013-09-06
    • 1970-01-01
    相关资源
    最近更新 更多