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

当前回答

你可以在你的React应用程序中使用Vercel的主机,并使用相同的旧方式在你的React应用程序中使用BrowserRouting。

您需要添加一个vercel。Json文件在你的项目的根,并添加以下代码:

{
  "rewrites": [
    {
      "source": "/((?!api/.*).*)",
      "destination": "/index.html"
    }
  ]
}

这工作得非常好。

其他回答

如果你在IIS中托管:将此添加到我的webconfig解决了我的问题

<httpErrors errorMode="Custom" defaultResponseMode="ExecuteURL">
    <remove statusCode="500" subStatusCode="100" />
    <remove statusCode="500" subStatusCode="-1" />
    <remove statusCode="404" subStatusCode="-1" />
    <error statusCode="404" path="/" responseMode="ExecuteURL" />
    <error statusCode="500" prefixLanguageFilePath="" path="/error_500.asp" responseMode="ExecuteURL" />
    <error statusCode="500" subStatusCode="100" path="/error_500.asp" responseMode="ExecuteURL" />
</httpErrors>

您可以为任何其他服务器进行类似的配置。

这可以解决你的问题。

在生产模式下的React应用程序中,我也遇到了同样的问题。这里有两个解决这个问题的方法。

解决方案1。将路由历史更改为“hashHistory”,而不是browserHistory

<Router history={hashHistory} >
   <Route path="/home" component={Home} />
   <Route path="/aboutus" component={AboutUs} />
</Router>

现在使用命令构建应用程序

sudo npm run build

然后将构建文件夹放在var/www/文件夹中。现在,在每个URL中添加#标签,应用程序就可以正常工作了。就像

localhost/#/home
localhost/#/aboutus

解决方案2:没有#标签使用browserHistory,

在路由器中设置你的history = {browserHistory}。现在使用sudo npm run build构建它。

您需要创建“conf”文件来解决404 not found页面。conf文件应该是这样的。

打开终端,输入以下命令

cd /etc/apache2/sites-available
ls
nano sample.conf

在其中添加以下内容

<VirtualHost *:80>
    ServerAdmin admin@0.0.0.0
    ServerName 0.0.0.0
    ServerAlias 0.0.0.0
    DocumentRoot /var/www/html/

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
    <Directory "/var/www/html/">
            Options Indexes FollowSymLinks
            AllowOverride all
            Require all granted
    </Directory>
</VirtualHost>

现在您需要使用以下命令启用sample.conf文件:

cd /etc/apache2/sites-available
sudo a2ensite sample.conf

然后,它将要求您重新加载Apache服务器,使用

sudo service apache2 reload or restart

然后打开您的localhost/build文件夹,并添加包含以下内容的.htaccess文件。

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^.*$ / [L,QSA]

现在应用程序运行正常。

注意:0.0.0.0 IP地址修改为本地IP地址。

刷新DOM组件后无法得到403错误,这很简单。

只需在Webpack配置中添加这一行,'historyApiFallback: true '。这帮了我一整天的忙。

如果试图从IIS虚拟目录(不是网站的根目录)服务React应用程序:

在设置重定向时,'/'不会单独工作。对我来说,它也需要虚拟目录名。下面是我的网页配置:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <defaultDocument>
            <files>
                <remove value="default.aspx" />
                <remove value="iisstart.htm" />
                <remove value="index.htm" />
                <remove value="Default.asp" />
                <remove value="Default.htm" />
            </files>
        </defaultDocument>
        <rewrite>
            <rules>
                <rule name="React Routes" stopProcessing="true">
                    <match url=".*" />
                    <conditions logicalGrouping="MatchAll">
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                        <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="/YOURVIRTUALDIRECTORYNAME/" />
                </rule>
            </rules>
        </rewrite>
        <directoryBrowse enabled="false" />
        <httpErrors errorMode="Custom" defaultResponseMode="ExecuteURL">
            <remove statusCode="500" subStatusCode="100" />
            <remove statusCode="500" subStatusCode="-1" />
            <remove statusCode="404" subStatusCode="-1" />
            <remove statusCode="403" subStatusCode="18" />
            <error statusCode="403" subStatusCode="18" path="/YOURVIRTUALDIRECTORYNAME/" responseMode="ExecuteURL" />
            <error statusCode="404" path="/YOURVIRTUALDIRECTORYNAME/" responseMode="ExecuteURL" />
            <error statusCode="500" prefixLanguageFilePath="" path="/YOURVIRTUALDIRECTORYNAME/" responseMode="ExecuteURL" />
            <error statusCode="500" subStatusCode="100" path="/YOURVIRTUALDIRECTORYNAME/" responseMode="ExecuteURL" />
        </httpErrors>
    </system.webServer>
</configuration>

除了网络。配置文件,React应用程序本身需要一些改变:

在文件包中。Json,你需要添加一个'主页'条目:

{
  "name": "sicon.react.crm",
  "version": "0.1.0",
  "private": true,
  "homepage": "/YOURVIRTUALDIRECTORYNAME/",
  "dependencies": {
...

我将basename添加到我的浏览器历史对象中,并将其传递给路由器以访问历史:

import  {createBrowserHistory } from 'history';

export default createBrowserHistory({
    //Pass the public URL as the base name for the router basename: process.env.PUBLIC_URL
});

我还在我的React路由器文件App.js中添加了这个属性:

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

最后,在index.html文件中,我在'title'标签上方添加了以下选项卡:

<base href="%PUBLIC_URL%/">

也许有些步骤是不需要的,但这似乎已经完成了我的工作。我不知道如何设置它运行在一个站点的根目录或虚拟目录,而不需要重新编译,作为包中的主页。据我所知,json不能在构建后交换。

我刚刚用Create React App做了一个网站,也遇到了同样的问题。

我使用react-router-dom包中的BrowserRouting。我在Nginx服务器上运行,添加以下到/etc/nginx/yourconfig.conf为我解决了这个问题:

location / {
  if (!-e $request_filename){
    rewrite ^(.*)$ /index.html break;
  }
}

如果你正在运行Apache,这对应于在.htaccess中添加以下内容:

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

这似乎也是Facebook自己提出的解决方案。