What's the right way to set routing for angular2 with koajs

北城余情 提交于 2020-01-07 03:15:30

问题


I'm a newbie to angular2 and koajs. Maybe it's a silly question.

I have an angular2 app with a routing table as below:

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'
  },
];

If user access our app via the root url (http://localhost:3000), then navigate to a child page (eg: http://localhost:3000/pats/report/settings), everything is fine since angular2 app will deal with the child page navigation internally and will not issue a http request to backend.

But if user access our app with child page url directly, eg: http://localhost:3000/pats/report/settings, the backend koajs app will response with 404 status since it does not exist a route for path 'pats/report/settings' at the backend.

What's the right way to resolve this problem?

Should I add route for all client child page paths in the backend router and respond with the index.html?


回答1:


I dont know Koajs, but you need some middleware. Your backend needs to redirect those request to localhost:3000/ but let the URL as it is, so that angular can do its magic!

See this additional packages for koajs:

  • koa-repath
  • rewrite

The other option: Use Hashbang-URLs ! Angular2 URL-Styles



来源:https://stackoverflow.com/questions/39096211/whats-the-right-way-to-set-routing-for-angular2-with-koajs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!