构建应用程序后react-router不工作

IT技术 javascript reactjs npm build react-router
2021-04-28 05:46:27

我是react和react-router的新手。该应用程序是使用create-react-app 创建的我需要在我的应用程序中使用两个主要页面实现路由。我尝试了很多选项,最终使用以下代码使其工作。

此代码在开发过程中运行良好。但是在构建应用程序后,它无法正常工作。404 页面的路由只会显示出来。请帮我解决这个问题。

<Router history={browserHistory}>
  <Route component={Root}>
    <IndexRoute component={App} />
    <Route path="/" component={App} />
    <Route path="/sna/:country" component={SNA} />
    <Route path="*" component={FourOFour}/>
  </Route>
</Router>

我曾经browserHistory使用以下代码启用更改下拉列表的导航。

selectCountry(event){
    var value = event.target.value;
    browserHistory.push('/sna/' + value);
}

包.json

  {
  "name": "my-app",
  "version": "0.1.0",
  "homepage": "./",
  "private": true,
  "dependencies": {
    "bootstrap": "^3.3.7",
    "react": "^15.4.2",
    "react-addons-update": "^15.4.2",
    "react-bootstrap": "^0.30.8",
    "react-data-grid": "^2.0.24",
    "react-dom": "^15.4.2",
    "react-router": "^2.6.0"
  },
  "devDependencies": {
    "react-scripts": "0.9.5"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}
4个回答

这是一个与服务器相关的问题

对于 Apache 服务器:

确保您的 Apache 服务器将每个请求重定向到 index.html 文件。确保以下代码存在于 .htaccess 中

Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]

在坚持react-router了几天之后,我阅读了React Training 中的文档然后我按照快速入门步骤对其进行了修改以满足我的要求。

import {
  HashRouter as Router,
  Route,
  } from 'react-router-dom';

  <Router>
    <div>
      <Header />
      <Route exact path="/" component={Content} />
      <Route path="/:country" component={SnaContent} />
      <Footer />
    </div>
  </Router>

这暂时解决了这个问题。希望对遇到类似问题的其他人有所帮助。

编辑:

最好的方法是使用公共 URL,它将被部署为组件中basenameprop Router它也可能类似于PUBLIC_URL=myproject,并且假设应用程序在https://<domain-name>/myproject/index.html.

<Router basename={process.env.PUBLIC_URL}>
...
</Router>

旧答案:

首先,这不是 React Router 的问题。请注意,在您的 中package.json,您有:

  "homepage": "./",
  "private": true,

简短的回答是,如果您更改"homepage"和 make it的值"",或实际部署它的站点的主页的 URL,它将直接工作。

"homepage": "",

或者

"homepage": "mysite.com/",

这就是我认为有效的原因,详细说明:

如果您现在使用react-scripts build,它会创建一个文件 -build/index.html导入 .js 文件之类的 JS 文件<script src="./static/js/main.9ea6b007.chunk.js">

现在,当您使用 react-router 时,理想情况下您希望将所有请求路由到build/index.html. 因此,您可以构建一个代理服务器来为您的index.html静态文件提供如下服务(使用 Express.js):

const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');

const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use(express.static(path.join(__dirname, 'build')));

app.use('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'build/index.html'));
});

app.listen(process.env.PORT || 3000, () => console.log(`Running on PORT ${process.env.PORT || 3000}`));

现在您看到所有请求——除了静态文件的请求——都返回index.html文件。因此,当您请求/static/js/main.9ea6b007.chunk.js. 请注意这与您的index.html来源中的内容有何不同srcindex.html尝试从请求./static/...,并且.将被解释为当前路由。

因此,假设您要访问并localhost:3000/abcd期待您想要的页面出现。让我们来看看这里发生了什么。

  • 你得到了index.html你所期望的。
  • index.html试图要求./static/...,转化为localhost:3000/abcd/static/...,而你希望它是localhost:3000/static/...任何不一样的东西/static都将返回相同的内容index.html,因此即使是 JS 文件也会返回相同的页面,从而导致控制台错误Uncaught SyntaxError: Unexpected token '<'
  • 如果您转到浏览器 Devtools 并查看源代码,您的所有 JS 和 CSS 文件都将具有与index.html.

因此,homepagein yourpackage.json用作index.html所有静态文件的前缀,形式为<homepage>/static/.... 因此,它需要""使请求是/static/..."mysite.com/",以便请求是mysite.com/static/...

当我在 Firebase Hosting 上部署我的 React 应用程序时,我最初遇到了类似的问题。

事实证明,正如已接受答案的发布者所建议的那样,问题实际上不在于react-routerHashRouter 会在我们的 URL 前面附加 /#/,不管怎样,它看起来不是很漂亮。

我发现问题出在我们使用网络托管服务上我们需要指明我们想要呈现的默认 HTML 文件,即index.html

发生这种情况是因为我们的托管服务提供商(无论是 Amazon 的 S3 / Apache / Google Cloud Platform (GCP) 的 App Engine / Firebase Hosting 等)不知道如果 URL 不是默认 URL ( https ://www.link_to_your_website.com ) 已给出。例如,它将无法识别 https://www.link_to_your_website.com/login

在 Firebase 托管中,您需要执行以下操作:

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

在 Apache 的 .htaccess 中,您需要执行以下操作:

FallbackResource /index.html

来源:如何使用 .htaccess 将错误 404 重定向到主页?

这些命令会告诉他们无论如何都要渲染 index.html,因为 React-Route 将使用新的 React 元素动态更新 HTML DOM 的树。

希望那些遇到过类似问题的人会发现这很有帮助。