Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deploy Angular2 App to Tomcat8 - Routing does not seems to work

I'm facing a strange issue trying to deploy my Angular2 app to tomcat8.

First of all the context : - I use Angular Cli to assit my build process. - The apps runs perfectly locally with the server : ng serve - ng build makes my dist/ dir with all prod ressources - I created a gulp task to create a WAR in order to deploy properly the app to Tomcat. - the war is deployed to tomcat webapps directoy

My app URI is like that : https:\www.myexample.com\myapp\

Home uri is working perfectly; The problem starts when trying to use Angular2 routing; for instance https:\www.myexample.com\myapp\myroute.

Tomcats thinks that it is a new webapp dir and does not makes any forwarding do https:\www.myexample.com\myapp\index.html

I have seen several post speaking about this kind of behaviour but so far; I haven't seen any solutions.

does anyone has a clue / idea how I can overcome this issue to run properly my angular2 app on tomcat8 ?

Thanks for support.

like image 482
aorfevre Avatar asked Jan 04 '17 20:01

aorfevre


2 Answers

You need to rewrite the urls to serve index.html unless the dir or file exists.

Configure Tomcat to use the rewrite valve https://tomcat.apache.org/tomcat-8.0-doc/rewrite.html

Then add the something like below to the rewrite.config file:

# If dir or asset exists go to it
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
# Rewrite all other urls to use index.html
RewriteRule ^ /index.html
like image 125
shusson Avatar answered Sep 30 '22 15:09

shusson


Adding RouterModule.forRoot(useHash: true) switches to URLs using # which works with every server.

To use HTML5 pushState (Angular default) your server needs to be configured to support it.

For a comparison of both styles see https://angular.io/docs/ts/latest/guide/router.html#!#browser-url-styles

like image 28
Günter Zöchbauer Avatar answered Sep 30 '22 16:09

Günter Zöchbauer