Spring Boot整合Angular,將Restful API以外的路由導向Angular (Gradle專案可用)
前言
雖然沒特別試,但推測React.Js、Vue.Js應也能達到同樣效果!
花了好多時間,總算找到一個最簡單的解法,實測成功!
期望結果:
- Spring Boot為Gradle專案亦能使用,不必透過maven-resources-plugin
- 於瀏覽器重新整理,如https://localhost:8080/user,仍會回到目前頁面,不會跳出Spring Boot預設的Whitelabel Error Page
- 將端框架打包後的輸出檔,置於外部路徑。不必與Spring Boot一起打包。純修正前端頁面的話,不須中斷服務 (可選,詳見補充)
作法
一、增加FrontendController.java
- 增加的Controller,implement ErrorController
- 增加Get路由/error,回傳forward:index.html
@Controller
public class FrontendController implements ErrorController {
    @GetMapping(value = "/error")
    public String home() {
        return "forward:index.html";
    }
}關於ErrorController
可以參考Spring Boot: Customize Whitelabel Error Page獲得更詳細資訊
二、application.yaml增加靜態資源,將前端框架路徑置於外部(可選)
於application.yaml增加static-locations增加外部路徑
以D:/MY_APP/frontend為例,請記得改成自己要的路徑
yaml:
spring:
    resources:
        static-locations: file:D:/MY_APP/frontendproperties:
spring.resources.static-locations=file:D:/MY_APP/frontend前端框架打包後的檔案,直接將所有檔案丟至該目錄(即範例的D:/MY_APP/frontend)
不需要再多一層目錄
否則於在瀏覽器導向頁面會變成http://localhost:8080/FOLDER_NAME/index.html
而因HTML裡的base-href預設為/,會導致無法取得所有js、css,畫面就會一片空白
若這就是期望的輸出結果,Angular 打包時記得加上base-href參數
於package.json -> script -> build補上參數
即:ng build --base-href=/FOLDER_NAME/
補充
若不打算將前端框架置於外部的話
記得把前端框架打包後的檔案放到Spring Boot預設serve靜態資源的路徑即可,如下:
/META-INF/resources/
/resources/
/static/
/public/參考資料
Stack Overflow / Spring Boot with redirecting with single page angular2
Spring Boot: Customize Whitelabel Error Page