Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot 2.1.0 only serve index.html if resource not resolved (SPA, react-router)

I am serving an SPA made with create-react-app and react-router using Spring Boot 2.1.0 with this configuration

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/**/{path:[^\\.]+}")
                .setViewName("forward:/");
    }
}

Basically what it does is always serve index.html unless there's a period in the path. I would like to align this with create-react-app's provided .htaccess. How can I make Spring Boot match this functionality?

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
like image 214
Roberto Graham Avatar asked Nov 20 '18 12:11

Roberto Graham


2 Answers

To reroute "404 : file not found" to "forward:/", which I think is what the .htaccess does, change your WebMvcConfiguration to...

@Configuration
public class WebMvcConfiguration implements ErrorViewResolver
{

    @Override
    public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {
        if (status == HttpStatus.NOT_FOUND) {
            return new ModelAndView("forward:/");
        }
        return null;
    }

}
like image 100
pcoates Avatar answered Oct 15 '22 19:10

pcoates


You can catch-all unhandled view controller like below when no other route has been found.

@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
       registry.setOrder(Ordered.LOWEST_PRECEDENCE);
        registry.addViewController("/**").setViewName("forward:/index.html");
    }
}
like image 2
Sukhpal Singh Avatar answered Oct 15 '22 19:10

Sukhpal Singh