1. 程式人生 > >【SpringBoot】vue重新整理頁面404錯誤,自定義指向頁面

【SpringBoot】vue重新整理頁面404錯誤,自定義指向頁面

問題描述

     將vue專案整合進後端專案,部署伺服器後,正常使用沒有問題,但是隻要重新整理當前頁面就總是返回404錯誤,Whitelabel Error Page,This application has no explicit mapping for /error, so you are seeing this as a fallback。上網檢視很多原因,有的說是沒有配置檢視解析器,有的說是application啟動類放置的位置不對,有的說是controller的路徑寫的不對造成的。

問題原因

      我理解的原因是,正常情況下我們重新整理頁面,那麼瀏覽器就會按照url去後臺請求資料。但是在vue專案中,url只是在router中定義的跳轉路徑(並不是controller中的mapping),當跳轉到某頁面之後會在呼叫api(比如說在created的時候)去後臺請求資料。那麼我們重新整理頁面, 瀏覽器會認為url是對應controller中的mapping,但實際上後臺根本沒有對應的方法,因此報錯。

解決辦法

      vue專案與後端專案整合是通過install打包前端專案,然後把打包完產生的dist資料夾下的static資料夾和index.html放到後端專案的static路徑下,其實最終整個前端專案都被編譯成js檔案,由index.html進行渲染。因此我這裡通過捕獲404HTTP錯誤狀態碼自定義頁面,將頁面指向了index.html,由其進行解析。解決辦法就是在啟動類加上如下程式碼:

@Bean
public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer(){
	return factory -> {
           ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/index.html");
           factory.addErrorPages(error404Page);
	};
}

      需要注意的是,這是SpringBoot版本在2.0以上的寫法。2.0之後EmbeddedServletContainerCustomizer 類被WebServerFactoryCustomizer取代了。2.0以下的可以參考如下程式碼:

@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {

   return (container -> {
        ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/401.html");
        ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/404.html");
        ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500.html");

        container.addErrorPages(error401Page, error404Page, error500Page);
   });
}

      自定義頁面需放在static目錄下,預設路徑為src/main/resources/static