0

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?

ricky
  • 2,058
  • 4
  • 23
  • 49

1 Answers1

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:

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

slaesh
  • 16,659
  • 6
  • 50
  • 52
  • Checked [Angular2 URL-Styles](https://angular.io/docs/ts/latest/guide/router.html#!#browser-url-styles), and it seems that Hashbang-URL is not recommended. – ricky Aug 23 '16 at 09:09
  • Yeah, just wanted to show you that option too. Best practice would be the correct handling of `unknown URLs` via your koajs-backend. – slaesh Aug 23 '16 at 12:25
  • I've tried koa-repath, it works well! Thanks again, @mxii – ricky Aug 24 '16 at 09:06