Wildcard route added but still for undefined route Cannot GET /

735 Views Asked by At

I am using Angular 6 in my project. I Added wildcard route but still iam facing the error when i go to any undefined route angular gives Cannot GET /<path> in browser.

Below is my routes, all other defined routes are working perfectly fine but wildcard not working

const AppRoutes: Routes = [
 { path: '', redirectTo: 'login', pathMatch: 'full' },
 { path: "register", component: RegisterComponent },
 { path: "login", component: LoginComponent },
 { path: "dashboard", component: DashboardComponent, canActivate: [AuthGuard] },
 { path:"backup",component:BackupComponent},
 { path: '**', component: NotFoundComponent },
];

Routes are imported as default..

imports: [
 BrowserModule,
 ReactiveFormsModule,
 NgxPaginationModule,
 .
 .
 . 
 RouterModule.forRoot(AppRoutes),
],

For some reason i could not use hash based routing

//Can not use hash base routing in my case
RouterModule.forRoot(AppRoutes, { useHash: true }),

I believe wildcard should work without hash based routing. Let me know where i am going wrong.

3

There are 3 best solutions below

0
On BEST ANSWER

I was running the app with backend in NodeJS, running Angular and Node at same port through ng-build and node app.js When i run angular with ng serve it works fine, but not with ng build, but in production everythings seem good and wildcard working as expected.

1
On

There seems to be no issue with your defined routes. However, check this article for issue with your hash based routing.

0
On

This you can try to solve in 2 ways:

  1. Try to change the order of parent route and wild card route such as
const AppRoutes: Routes = [
 { path: "register", component: RegisterComponent },
 { path: "login", component: LoginComponent },
 { path: "dashboard", component: DashboardComponent, canActivate: [AuthGuard] },
 { path:"backup",component:BackupComponent},
 { path: '', redirectTo: 'login', pathMatch: 'full' },
 { path: '**', component: NotFoundComponent },
];
  1. Make use of redirectTo for NotFoundComponent.

Please check this article for more details WildCardRoutes

Thanks