React Router v6在Spring Boot应用中路由失效,出现白标404错误
解决方案:Spring Boot + React 前端路由404问题
问题原因
React的BrowserRouter属于前端路由,当直接访问/about这类路径时,Spring Boot会将其视为后端接口请求,找不到对应映射就返回404白标页面。需要让Spring Boot把所有非API的前端路由请求转发到index.html,由React接管路由处理。
步骤1:修正Maven复制资源配置
你pom.xml里的<filtering>true</filtering>会破坏React打包后的静态文件(比如替换JS/CSS里的变量),改成false:
<execution> <id>copy-resources</id> <phase>process-resources</phase> <goals> <goal>copy-resources</goal> </goals> <configuration> <outputDirectory>${basedir}/target/classes/static</outputDirectory> <resources> <resource> <directory>src/main/webapp/build</directory> <filtering>false</filtering> <!-- 关键修改 --> </resource> </resources> </configuration> </execution>
步骤2:配置Spring Boot路由转发
创建WebConfig类,将所有非API请求转发到index.html:
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { // 排除/api开头的后端接口,其余请求转发到index.html registry.addViewController("/**") .setViewName("forward:/index.html") .setCustomCondition(request -> !request.getRequestURI().startsWith("/api")); // 确保根路径正常访问 registry.addViewController("/").setViewName("forward:/index.html"); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // 配置静态资源访问路径 registry.addResourceHandler("/**") .addResourceLocations("classpath:/static/"); } }
如果没有后端API接口,可以简化为:
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 WebConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/**").setViewName("forward:/index.html"); } }
步骤3:调整React路由配置
React Router v6中exact已经默认生效,不需要手动添加,简化你的App.js:
<div> <NavMain /> <BrowserRouter> <Routes> <Route path="/" element={<WelcomePage />} /> <Route path="/about" element={<AboutPage />} /> </Routes> </BrowserRouter> </div>
步骤4:确保React打包配置正确
在React项目的package.json中添加homepage字段,避免静态资源路径错误:
{ "name": "your-react-app", "homepage": ".", // 添加这一行 // ...其他配置 }
然后重新执行React打包:
npm run build
最后重启Spring Boot项目,访问/about等路由即可正常跳转。
内容的提问来源于stack exchange,提问作者ksernow
相关产品推荐
相关产品推荐

