You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 15:01:04