404: Deploy Angular Project on Tomcat?

Viewed 502

I have developed a Project in Angular and built it with the command ng build --base-href /myApp/. Then I have deployed it on my Tomcat-Server, after refreshing a page of my myApp I get 404 not found. I know that the server doesn't know the client-side routing, so I have to tell him that he has to go back to "index.html".

That's why I have configured my "tomcat/conf/web.xml" like this:

<error-page> 
    <error-code>404</error-code>
    <location>/myApp/index.html</location>
</error-page>

But the issue still comes up.

Have you any idea how to solve this problem?

1 Answers

You need to re-route to index.html. This is a known issue and you can find more info in this link. Also i would recommend using urlrewrite and grunt for copying the required files.

First you need to create a folder called WEB-INf. Inside that folder you need to put the urlrewrite library and the urlrewrite.xml file. Using grunt you can create a war file with all, including angular dist folder using commands.

This is an example of the urlrewrite.xml file:

<urlrewrite>

<rule match-type="wildcard">
    <from>
        /home //example route, all www.yourapp.com/home would redirect to home using the index.html
    </from>
    <to last="true">
        index.html
    </to>
</rule>
<rule match-type="wildcard">
    <from>
        /otherroute  //same but with other route and no using * wont work
    </from>
    <to last="true">
        index.html
    </to>
</rule>

this an example of the gruntfile.js:

module.exports = function(grunt) {

grunt.loadNpmTasks('grunt-war');

grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    war: {
        target: {
            options: {
                war_dist_folder: 'dist', //war creation destination
                war_name: 'warname',
                webxml_display_name: 'YourAppsname',
                webxml_webapp_version: 'YoursAppversionnumber',
                webxml_webapp_extras: [
                    "<filter>\n<filter-name>UrlRewriteFilter</filter-name>\n<filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>\n</filter>\n<filter-mapping>\n<filter-name>UrlRewriteFilter</filter-name>\n<url-pattern>/*</url-pattern>\n<dispatcher>REQUEST</dispatcher>\n<dispatcher>FORWARD</dispatcher>\n</filter-mapping>"
                ],
            },
            files: [{
                    expand: true,
                    cwd: 'dist',
                    src: ['**'],
                    dest: ''
                },
                {
                    expand: true,
                    cwd: 'src/assets/deployment', //folder where the lib folder and urlrewrite.xml file are in your project
                    src: ['**'],
                    dest: 'WEB-INF'
                }
            ]
        }
    }
});

grunt.registerTask('default', ['war']);};

And this is the running command:

ng build --prod --base-href=/yourapphref/ && grunt
Related