我正在使用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);
});

当前回答

我喜欢这种处理方式。尝试添加: yourSPAPageRoute/*在服务器端消除这个问题。

我采用了这种方法,因为即使是原生HTML5 History API也不支持页面刷新时的正确重定向(据我所知)。

注意:选定的答案已经解决了这个问题,但我试图更具体。

表达的路线

其他回答

在index.html文件头部,添加以下内容:

<base href="/">
<!-- This must come before the CSS and JavaScript code -->

然后,当与Webpack开发服务器一起运行时,使用此命令。

webpack-dev-server --mode development --hot --inline --content-base=dist --history-api-fallback

-history-api-fallback是重要的部分

HashRouter的实现很简单,

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


  function App() {
  return (
    <Router>
        <Switch>
          <Route path="/" exact component={InitialComponent} />
          <Route path="/some" exact component={SomeOtherComponent} />
        </Switch>
      </Router>
  );
}

它在浏览器中是这样的 Http:localhost:3000/#/, Http:localhost:3000/#/some

如果你使用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” 这种方法是万能的,可能是最简单的入门方法。

如果你在IIS上托管React应用程序,只需添加一个web。配置文件包含:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.webServer>
        <httpErrors errorMode="Custom" existingResponse="Replace">
            <remove statusCode="404" subStatusCode="-1" />
            <error statusCode="404" path="/" responseMode="ExecuteURL" />
        </httpErrors>
    </system.webServer>
</configuration>

这将告诉IIS服务器将主页返回给客户端,而不是404错误,并且不需要使用哈希历史。

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

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

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

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

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

错误页403规则