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

当前回答

在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是重要的部分

其他回答

这可以解决你的问题。

在生产模式下的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地址。

当我使用apache(Httpd)服务器时,我也面临同样的问题。我解决了咆哮这种方式,为我工作100%。

步骤1:

进入/etc/httpd/conf/httpd.conf /对于新版本,进入etc/apache2/apache2.conf 将AllowOverride None更改为AllowOverride All。 重启apache服务器。

步骤2:

构建完成后,将.htaccess文件放入根文件夹。

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

我使用的是。net Core 3.1,只是添加了扩展MapFallbackToController:

文件Startup.cs

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");

        endpoints.MapFallbackToController("Index", "Home");
    });

如果你在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错误,并且不需要使用哈希历史。

我们使用Express.js的404处理方法。

// Path to the static React build directory
const frontend = path.join(__dirname, 'react-app/build');

// Map the requests to the static React build directory
app.use('/', express.static(frontend));

// All the unknown requests are redirected to the React SPA
app.use(function (req, res, next) {
    res.sendFile(path.join(frontend, 'index.html'));
});

这招很管用。现场演示是我们的网站。