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

React Router搭配Spring Boot后端手动访问路由异常问题

问题:跨应用跳转React路由部署后失效的解决办法

我有一个React UI,可通过localhost/app1的按钮打开新标签页跳转到localhost/app2/usersettings。开发环境下正常,但打包部署后失效,会直接重定向回localhost/app2。

  • 在app2内点击跳转至/usersettings正常
  • 手动输入URL或从app1跳转时,仅加载首页

当前配置

Spring Boot 配置

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addRedirectViewController("/","index.html");
    registry.addRedirectViewController("/usersettings","index.html?path=usersettings");
    registry.addRedirectViewController("/{x:[\\w\\-]+}","index.html");
    registry.addRedirectViewController("/{x:^(?!api$).*$}/**/{y:[\\w\\-]+}", "index.html");
}

React 路由配置

const MainPage = () => {
    return (
        <Box>
            <CssBaseline/>
            <Routes>
                <Route path="/" element={<HomePage/>}/>
                <Route path="index.html" element={<Navigate to="/"/>}/>
                <Route path="/usersettings" element={<UserSettings/>}/>
            </Routes>
        </Box>
    );
};

问题原因与修复方案

1. 修正Spring Boot的路径处理逻辑

当前配置用了addRedirectViewController,会把请求重定向到index.html,导致浏览器地址栏的原始路径被替换,React路由无法获取正确的路径信息。同时通配规则/{x:[\\w\\-]+}会覆盖/usersettings的重定向配置,最终所有单级路径都被重定向到根路径的index.html。

修复方式:改用addViewController做服务器内部转发,保留浏览器地址栏的原始路径,让React路由自行匹配:

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    // 根路径转发到index.html
    registry.addViewController("/").setViewName("forward:/index.html");
    // 匹配所有非API的路径,转发到index.html(保留原始请求路径)
    registry.addViewController("/{x:^(?!api$).*$}").setViewName("forward:/index.html");
    registry.addViewController("/{x:^(?!api$).*$}/**").setViewName("forward:/index.html");
}

2. 确保React路由的基础配置正确

  • 确认使用BrowserRouter包裹路由(而非HashRouter),保证基于浏览器路径的路由匹配:
    import { BrowserRouter } from 'react-router-dom';
    
    ReactDOM.render(
      <BrowserRouter>
        <MainPage />
      </BrowserRouter>,
      document.getElementById('root')
    );
    
  • 保留index.html的跳转规则即可,因为转发后浏览器地址栏不会出现该路径,不影响正常路由匹配。

3. 验证跨应用跳转的路径正确性

app1中的跳转按钮需使用完整的绝对路径:

<button onClick={() => window.open('http://localhost/app2/usersettings', '_blank')}>
  打开用户设置
</button>

部署后确认服务器正确处理静态资源,且Spring Boot的转发规则不会拦截API请求(当前配置的^(?!api$)已排除API路径,符合需求)。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 15:42:49