Spring Boot整合React刷新页面出现Whitelabel Error Page问题求助
解决Spring Boot与React前端路由刷新404问题
问题原因
React的BrowserRouter属于前端路由,页面内导航是通过JS切换组件,不会向后端发起请求。但刷新页面或手动输入子路由(如/TestDX/secondo)时,浏览器会直接向Spring Boot后端发送GET请求,后端没有对应路由映射,因此返回Whitelabel错误页。
Spring Boot端解决方案
方案一:创建路由转发Controller
编写一个Controller,捕获所有/TestDX下的子路径请求,转发到React的入口页面index.html:
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/TestDX") public class ReactRouteForwardController { // 匹配/TestDX下的所有子路径 @GetMapping(value = "/**") public String forwardToReact() { // 转发到React的index.html,需确保该文件在Spring Boot静态资源目录的/TestDX下 return "forward:/TestDX/index.html"; } }
方案二:通过WebMvcConfigurer全局配置
实现WebMvcConfigurer接口,配置全局视图控制器,统一转发前端路由请求:
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 WebMvcConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { // 将/TestDX下的所有请求转发到React入口页面 registry.addViewController("/TestDX/**") .setViewName("forward:/TestDX/index.html"); } }
额外注意事项
- 确保React打包后的静态资源(包括
index.html)放在Spring Boot的src/main/resources/static/TestDX目录下,这样后端能正确找到入口页面。 - React项目打包前,需在
package.json中设置"homepage": "/TestDX/",确保打包后的资源路径自动带上/TestDX前缀,避免静态资源加载失败。
内容的提问来源于stack exchange,提问作者Alextave
相关产品推荐
相关产品推荐

