refreshing the page results in 404 error- Angular 6

后端 未结 10 1734
广开言路
广开言路 2020-12-05 06:54

I am building an application with the help of Angular6 and facing problems in routing. All the routes are working when I click on a particu

10条回答
  •  失恋的感觉
    2020-12-05 07:22

    I think you are getting 404 because your are requesting http://localhost/route which doesn't exist on tomcat server. As Angular 2 uses html 5 routing by default rather than using hashes at the end of the URL, refreshing the page looks like a request for a different resource.

    When using angular routing on tomcat you need to make sure that your server will map all routes in your app to your main index.html while refreshing the page. There are multiple way to resolve this issue. Whichever one suits you you can go for that.

    1) Put below code in web.xml of your deployment folder :

    
         404
         /index.html
    
    

    2) You can also try using HashLocationStrategy with # in the URL for routes :

    Try using:

    RouterModule.forRoot(routes, { useHash: true })

    Instead of:

    RouterModule.forRoot(routes)

    With HashLocationStrategy your urls gonna be like:

    http://localhost/#/route

    3) Tomcat URL Rewrite Valve : Re-write the url's using a server level configuration to redirect to index.html if the resource is not found.

    3.1) Inside META-INF folder create a file context.xml and copy the below context inside it.

    
    
      
    
    

    3.2) Inside WEB-INF, create file rewrite.config(this file contain the rule for URL Rewriting and used by tomcat for URL rewriting). Inside rewrite.config, copy the below content:

    RewriteCond %{SERVLET_PATH} !-f

    RewriteRule ^/(.*)$ /index.html [L]

提交回复
热议问题