ReactJS:打开 /about 页面时获取 404

ReactJS: Getting 404 when a /about page is opened

这是我第一次将 React Web App 部署到 firebase 托管。在我的 index.html 文件中,我只有根目录 div:

<body>
    <div id="root" class="container"></div>
</body>

这就是体内的全部。然后我在 src 文件夹中有一个 index.js 我有:

import { BrowserRouter as Router, Route } from "react-router-dom";'
import HomeScreen from "./screens/HomeScreen";
import AboutScreen from "./screens/AboutScreen";
...
ReactDOM.render(
    <Router>
        <div>
            <Route exact path="/" component={HomeScreen} />
            <Route exact path="/about" component={AboutScreen} />
        </div>
    </Router>,
    document.getElementById("root"))

然后打开关于页面,我将其链接为:

import { Container, Nav, Navbar } from 'react-bootstrap';
...
<Nav.Link href="/about">About</Nav.Link>

当我执行 npm run build 然后 firebase deploy 部署时,我可以在主页上看到更改。但是当我点击 about 它给了我 404

我有一个名为 build 的文件夹,它是 public 文件夹,在构建之后,它只有 index.html404.html 以及一个 static/js生成了一些 jstxt.

的文件夹

所以,我不确定为什么会收到 404。在开发版本中,即 localhost 导航工作正常。

那是因为是静态部署的单个index.htmlabout.html不存在,只能访问index.html,其他视图“不存在” t”因为是单页应用程序,但您可以将“/”以外的所有 URL 重定向到 index.html 文件,编辑 firebase.json

"rewrites": [ {
  "source": "**",
  "destination": "/index.html"
} ]

对于单页应用,必须指定重定向规则。 每条路线都应从 index.html 文件

重定向

您需要指定正在部署的部署目录和重定向规则

这是我的 React 应用程序,与 firebase 函数一起部署到 firebase 托管

{
  "hosting": {
    "public": "build",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  },
  "firestore": {
    "rules": "firestore.rules",
    "indexes": "firestore.indexes.json"
  }
}