React Router部署时无法直接访问子页面

React Router fail to direct access subpage when deployed

当我在本地主机上工作时,使用 create-react-app

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

但是当我将其部署到服务器时,npm build 运行 并将构建的文件放入服务器文件夹,如 https://ip/project_name

我可以点击 <Link/> 转到 https://ip/project_name/A or https://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

<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"
}

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

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

问题出在server文件夹,react router设置正确

为了子孙后代:

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

应该可以解决您的问题。

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

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

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

只使用不带基本名称的 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