【问题标题】:React Router fail to direct access subpage when deployedReact Router 部署时无法直接访问子页面
【发布时间】:2020-05-03 22:47:09
【问题描述】:

当我在 localhost 中工作时,使用 create-react-app

我可以访问 localhost:3000/A 或 localhost:3000/B

但是当我将它部署到服务器时,npm build run 并将构建的文件放到服务器文件夹中,例如 https://ip/project_name

我可以点击<Link/> 转到https://ip/project_name/Ahttps://ip/project_name/B 但我无法直接访问https://ip/project_name/A

App.js

<BrowserRouter basename={'project_name'}>
    <Route path='/A' component={A}/>
    <Route path='/B' component={B}/>
</BrowserRouter>

链接

<Link to="/A">A</Link>
<Link to="/B">B</Link>

package.json

"homepage": ".",
...
"dependencies": {
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-router-dom": "^5.1.2",
    "react-scripts": "3.2.0"
}

【问题讨论】:

    标签: reactjs routes react-router web-deployment webdeploy


    【解决方案1】:

    只需使用没有 basename 的 HashRouter 而不是 BrowserRouter:

    import { HashRouter, Route } from 'react-router-dom';
    
    // Then in render
    <HashRouter>
      <Route path='/' component={ Home } exact />
      <Route path='/contact' component={ Contact} exact />
    </HashRouter>
    

    请注意,您将在 URL 中包含 /#/:

    http://server.com/path/#/contact

    【讨论】:

      【解决方案2】:

      为了后代:

      您必须在您的网络服务器中添加一个重写规则:例如,将 /* 重写为 /index.html

      应该可以解决你的问题。

      为什么: 对于具有动态(反应)页面的静态站点,Web 服务器仅提供主文件 index.html 和一些静态文件,如 css、图像等。

      加载 index.html 后,react-router 会根据 url 路径上的资源路径选择正确的页面。

      如果没有重写规则,像 https://ip/project_name/A 这样的路径会在服务器上请求资源“A”。所以 index.html 永远不会被检索到,你会得到一个 404 状态码。

      【讨论】:

        【解决方案3】:

        问题出在 server 文件夹,react 路由器设置正确。

        【讨论】:

          【解决方案4】:

          您是否尝试过使用字符串作为 basename 属性?

          <BrowserRouter basename="project_name">
              <Route path='/A' component={A}/>
              <Route path='/B' component={B}/>
          </BrowserRouter>
          

          【讨论】:

          • 两者都一样
          猜你喜欢
          • 2018-03-01
          • 1970-01-01
          • 2017-03-17
          • 2022-10-24
          • 1970-01-01
          • 2019-07-24
          • 1970-01-01
          • 2023-03-05
          • 2018-03-06
          相关资源
          最近更新 更多