Configure Spring Boot for SPA frontend

前端 未结 3 735
谎友^
谎友^ 2020-12-10 19:21

I have application where whole frontend part is laying in resource. I would like to separate things apart. And have separate server for UI, provided by gulp, for example.

相关标签:
3条回答
  • 2020-12-10 19:42

    If you are using Angular with Spring Data Rest, I think that the most straightforward way to do it is using angular hash location strategy.

    Just putting this in the providers array in your app module:

    { provide: LocationStrategy, useClass: HashLocationStrategy }

    and, obviously, import it.

    0 讨论(0)
  • 2020-12-10 19:44

    For routing, according to this guide at Using "Natural" Routes (specifically here), you have to add a controller that does the following:

    @Controller
    public class RouteController {
        @RequestMapping(value = "/{path:[^\\.]*}")
        public String redirect() {
            return "forward:/";
        }
    }
    

    Then using Spring Boot, the index.html loads at /, and resources can be loaded; routes are handled by Angular.

    0 讨论(0)
  • 2020-12-10 19:58

    EpicPandaForce has a great answer, and I wanted to expand on it. The following endpoint will allow matching on nested routes as well. If you wanted to have an admin section, you can configure it to return a different index.html.

    @Controller
    class PageController {
    
        @GetMapping("/**/{path:[^\\.]*}")
        fun forward(request: HttpServletRequest): String? {
            if(request.requestURI.startsWith("/admin")) {
                return "forward:/admin/index.html"
            }
            return "forward:/index.html"
        }
    }
    

    This RequestMapping (or @GetMapping) works by excluding any request that contains a period (i.e. "index.html").

    0 讨论(0)
提交回复
热议问题