Spring Boot/Angular 4 - Routing in app hits the server

Black Dynamite picture Black Dynamite · Sep 11, 2017 · Viewed 10.2k times · Source

I have an Angular 4 (ES6) app that I want to serve from a Spring Boot application. My Angular app has an index.html, and when the address of http://localhost:8080 is hit, Spring Boot knows to map to the index.html file which in Angular is mapped to "/search".

However, I have another route called "adminlogin" which I would access through

http://localhost:8080/adminLogin

But in this instance, it hits my Spring Boot application, which doesn't have a mapping and then it throws an error.

How do I get my address of http://localhost:8080/adminLogin to go to my Angular app?

Answer

Avdhut Mankavale picture Avdhut Mankavale · Jul 16, 2018

I had the similar issue with my SpringBoot 2 and Angular6 app. I implemented the WebMvcConfigurer interface to override addResourceHandlers() method and redirect to index.html when there were no mappings found in spring controllers. this can be done in Spring boot 1.5.x extending the (now deprecated) WebMvcConfigurerAdaptor class. this is discussed in details in this stackoverflow thread: https://stackoverflow.com/a/46854105/2958428 I put my built angular app in this location target/classes/static using the outputPath field in angular.json (previously .angular-cli.json). Here's the sample code:

@Configuration
public class MyAppWebMvcConfigurer implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**/*")
            .addResourceLocations("classpath:/static/")
            .resourceChain(true)
            .addResolver(new PathResourceResolver() {
                @Override
                protected Resource getResource(String resourcePath, Resource location) throws IOException {
                    Resource requestedResource = location.createRelative(resourcePath);
                    return requestedResource.exists() && requestedResource.isReadable() ? requestedResource : new ClassPathResource("/static/index.html");
                }
            });
    }
}