繁体   English   中英

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

[英]ReactJS: Getting 404 when a /about page is opened

这是我第一次将 React Web 应用程序部署到 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

404错误图片

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

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

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

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

对于单页应用程序,必须指定重定向规则。 每个路由都应该从index.html文件重定向

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

这是我的反应应用程序与 firebase 功能一起部署到 firebase 托管

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM