首页 > 解决方案 > Spring Boot 上下文路径不适用于 React 浏览器路由器

问题描述

我有打包在 Spring Boot jar 中的 React 应用程序。build后jar里面的结构如下

/static/bundle.js
/static/index.html

在 Spring Boot 配置中渲染 UI 我添加了

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/").setViewName("forward:/index.html");
}

React 应用程序内部

<BrowserRouter basename="/">
  <Switch>
    <Route path="/" component={ShoppingCart} />
    <Route path="/recap" component={Recap} />
    <Route path="/confirm" component={ConfirmPayment} />
  </Switch>
</BrowserRouter>

这工作正常,我可以访问根路径 http://localhost:8088/ 上的应用程序。所有进一步的导航也像 /recap 一样工作。

现在我在 Spring 应用程序属性 server.servlet.contextPath=/demo中添加了上下文名称,代码更改如下

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/demo").setViewName("forward:/index.html");
}

<BrowserRouter basename="/demo">
      <Switch>
        <Route path="/" component={ShoppingCart} />
        <Route path="/recap" component={Recap} />
        <Route path="/confirm" component={ConfirmPayment} />
      </Switch>
</BrowserRouter>

这会在 http://localhost:8088/demo 成功呈现根页面但是如果我尝试导航到回顾屏幕 [history.push({pathname: "/recap" ....] 它无法找到路线. url 更改为 http://localhost:8088/demo/recap ,但页面未加载。

我已经搜索并尝试了许多不同的方法,但无法成功。

标签: reactjsspring-bootreact-router

解决方案


推荐阅读