我正在使用React-router,当我点击链接按钮时,它工作得很好,但当我刷新我的网页时,它没有加载我想要的东西。

例如,我在localhost/joblist和一切都很好,因为我到达这里按下一个链接。但如果我刷新网页,我会得到:

Cannot GET /joblist

默认情况下,它不是这样工作的。最初我有我的URL localhost/#/和localhost/#/joblist,他们工作得很好。但我不喜欢这种类型的URL,所以试图删除#,我写道:

Router.run(routes, Router.HistoryLocation, function (Handler) {
 React.render(<Handler/>, document.body);
});

这个问题不会发生在localhost/,这个总是返回我想要的。

这个应用程序是单页的,所以/joblist不需要向任何服务器询问任何事情。

我的整个路由器。

var routes = (
    <Route name="app" path="/" handler={App}>
        <Route name="joblist" path="/joblist" handler={JobList}/>
        <DefaultRoute handler={Dashboard}/>
        <NotFoundRoute handler={NotFound}/>
    </Route>
);

Router.run(routes, Router.HistoryLocation, function (Handler) {
  React.render(<Handler/>, document.body);
});

当前回答

如果你通过AWS Static S3 hosting和CloudFront托管React应用程序

这个问题由CloudFront以403 Access Denied消息响应,因为它期望/some/other/路径存在于我的S3文件夹中,但该路径只存在于React路由器的内部路由中。

解决方案是设置一个分发错误页面规则。转到CloudFront设置并选择您的发行版。接下来,进入“错误页面”选项卡。单击“创建自定义错误响应”,并添加403条目,因为这是我们获得的错误状态代码。

将响应页路径设置为/index.html,状态代码设置为200。

最终的结果让我惊讶于它的简单。索引页被提供,但URL保存在浏览器中,因此一旦React应用程序加载,它就会检测URL路径并导航到所需的路由。

错误页403规则

其他回答

将此添加到webpack.config.js:

devServer: {
    historyApiFallback: true
}

如果你使用Apache作为你的web服务器,你可以在你的。htaccess文件中插入这个:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-l
  RewriteRule . /index.html [L]
</IfModule>

我正在使用react:“^16.12.0”和react-router:“^5.1.2” 这种方法是万能的,可能是最简单的入门方法。

当我在Electron中使用React作为前端,使用React -router-dom作为路由时,我就遇到了这个问题。

我用HashRouter替换了BrowserRouter,这是固定的。

这里有一个简单的例子:

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

我通过修改webpack.config.js文件解决了这个问题。

我的新配置如下:

之前

output: {
  path: path.join(__dirname, '/build/static/js'),
  filename: 'index.js'
},


devServer: {
  port: 3000
}

output: {
  path: path.join(__dirname, '/build/static/js'),
  filename: 'index.js',
  publicPath: '/'
},


devServer: {
  historyApiFallback: true,
  port: 3000
}

在我的情况下,URL没有加载时,我使用一个参数。

作为权宜之计,我补充道 <基地href = " < yourdomain / IP > " > < /基础> 在build文件夹中index.html文件的<title>标签下。

这刚好解决了我的问题。