Make Spring Boot surrender routing control to Angular

featured_image

In a multi module application Spring Boot should surrender routing control to Angular, otherwise trying to access any route other than the root page will result in a Whitelabel Error Page:

"There was an unexpected error (type=Not Found, status=404)"

All paths supported by Angular are accessible when the app server is started with the following command:

However, when you build the whole project with Maven and run it, the app will break cause the Spring Boot will still be trying to manage paths by itself.

While the root path (e.g. http://localhost:8080/) will still work, accessing any other route (e.g. http://localhost:8080/dashboard) will give you the following error:

Error page screenshot

To fix it, you have to customize the MVC Configuration.

In a project built with Spring Boot 2.0.4 you can create a config directory and the MvcConfiguration class in it. The following code is responsible for redirecting all requests to the index.html – as a result, your Angular app will be able to handle them:

The "/**" path pattern will be matched by AntPathMatcher to zero or more directories in a path, so this configuration will be applied to all routes in our project. Next, a resolver – created with dependency to PathResourceResolver – will try to find a resource under the given location and all requests that are not handled by Spring Boot will be redirected to index.html allowing Angular to take care of them.

Remember to add @Configuration annotation and to implement the WebMvcConfigurer interface.

You can check out my example Angular Spring Boot scaffolding project and inspect the code from this post in the commit 3a57e01056c8183d87a9eb167aebd7994d23d55f.

This solution is based on this StackOverflow answer.

Photo by Matthew Henry on StockSnap

 

4 thoughts on “Make Spring Boot surrender routing control to Angular

Leave a Reply

Your email address will not be published. Required fields are marked *