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

Spring Boot集成React带参数路由出现404问题求助

React带参数路由在Spring Boot中404的原因及解决方法

问题原因

直接访问或刷新/scorecardview/:id、/update/:id这类带参数的路由时,浏览器会向Spring Boot服务器发起GET请求。Spring会优先匹配自身的控制器映射(你的API路径如/competition、/events等),找不到匹配的接口时就返回404,不会自动将请求转发到React的index.html,导致React Router无法接管路由处理。

而/、/create这类单层级路由能正常工作,是因为Spring找不到对应控制器时,会去静态资源目录查找index.html并返回,之后React Router就能正常处理。

解决方案

需要配置Spring Boot,将所有前端路由的请求(排除API接口)转发到index.html,让React Router处理。以下是两种常用方式:

方式一:创建SPA转发控制器

编写一个控制器,拦截所有非API的GET请求,转发到index.html:

@Controller
public class SpaForwardController {

    @GetMapping(value = "/**", produces = "text/html")
    public String forwardToIndex(HttpServletRequest request) {
        String requestUri = request.getRequestURI();
        // 排除所有后端API路径,避免影响接口调用
        String[] apiPrefixes = {"/competition", "/events", "/golfcourses", "/golfleaderboard", "/holes", "/players", "/scorecard", "/scores"};
        for (String prefix : apiPrefixes) {
            if (requestUri.startsWith(prefix)) {
                // 让Spring继续处理API请求,不存在则返回404
                return null;
            }
        }
        // 转发到index.html,交给React Router处理
        return "forward:/index.html";
    }
}

方式二:配置WebMvc视图控制器

通过实现WebMvcConfigurer,添加视图控制器规则,指定特定前端路由转发到index.html:

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        // 为带参数的路由添加转发规则
        registry.addViewController("/scorecardview/**").setViewName("forward:/index.html");
        registry.addViewController("/update/**").setViewName("forward:/index.html");
        // 可根据需要添加其他前端路由,如:
        // registry.addViewController("/create").setViewName("forward:/index.html");
    }
}

额外注意事项

  • 确保React项目使用的是BrowserRouter(而非HashRouter),这是单页应用路由的标准配置。
  • 确认src/main/resources/static下的index.html和bundle.js能正常访问,Spring Boot默认会自动映射该目录下的静态资源。

内容的提问来源于stack exchange,提问作者mvarta

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 14:17:30