Search code examples
angulardeploymentangular2-routingubuntu-18.04tomcat9

Angular routing not working when deployed to tomcat 9 (Ubuntu 18.04)


I coded an angular project on my own PC, everything worked fine when I ran it locally with the command ng serve. Now I want to deploy it on tomcat on a VM (provided by my school) because my project needs to be public.

I created a git repository and downloaded the angular project on the VM. Followed a tutorial to deploy the app in tomcat, which simply consisted of 2 steps:

  1. Run ng build --base-href=/angular/ to generate some files
  2. Copy the generated files to tomcat's /webapps subfolder

But it does not work as intended. To me it seems like there's an issue with routing.

Here's my routing module:

const appRoutes: Routes = [
  {path: 'coachPortal', component: CoachPortalComponent},
  {path: 'userPortal', component: UserPortalComponent},
  {path: 'users', component: UsersComponent},
  {path: 'userDetails/:id', component: UserDetailsComponent},
  {path: 'mySessions', component: MySessionsComponent},
  {path: '', redirectTo: '/coachPortal', pathMatch: 'full'},
  {path: '**', component: CoachPortalComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(appRoutes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

To navigate between routes, I use this old simple code: window.location.href = '/users';
This worked like a charm when I ran it locally on my pc.

But I'm guessing the reason why it's not working anymore after deploying on tomcat is because tomcat adds the prefix angular/.
When running locally on my pc the urls were localhost:4200/{componenturl}.
But on the VM it's x.x.x.x:8080/angular/{componenturl}

But because of the routing redirects I am getting 404 errors. When I first visit the root url x.x.x.x:8080/angular, it matches with the rule {path: '', redirectTo: '/coachPortal', pathMatch: 'full'}. and loads the coachPortal component and even changes the url to angular/coachPortal. But refreshing the page or manually entering angular/coachPortal gives a 404 error. And all other links don't work either.

Also on the coachPortal I have an image with src ../../../assets/logo.png and it obviously doesn't load because of how the generated files in webapps folder have different folder structure... How can I fix this? The image is directly under assets folder.


Solution

  • You can try use useHash: true. For me its working.

    Example:

    @NgModule({
        imports: [RouterModule.forRoot(routes, { useHash: true })],
        exports: [RouterModule],
    })
    

    and url on the VM will be x.x.x.x:8080/angular/#/{componenturl}