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

当前回答

修复在刷新或直接调用URL时“不能GET /URL”的错误。

配置你的webpack.config.js,以期望给定的链接像这样的路由。

module.exports = {
  entry: './app/index.js',
  output: {
       path: path.join(__dirname, '/bundle'),
       filename: 'index_bundle.js',
       publicPath: '/'
  },

其他回答

我通过修改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
}

如果你有一个回退到你的index.html,确保在你的index.html文件中你有这个:

<script>
  System.config({ baseURL: '/' });
</script>

这可能因项目而异。

通过以下对nginx配置的简单更改,我能够克服硬刷新web应用程序中断和手动URL输入web应用程序中断。

React版本:17.0.2 Web服务器:nginx 操作系统:Ubuntu Server 20.04 (Focal Fossa)

之前

location / {
    try_files $uri $uri/ =404;
}

location / {
    try_files $uri /index.html;
}

也许还有其他的解决方法,但是这个方法对我来说非常快速和节省时间。

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

如果你正在使用nginx托管,需要快速修复…

在你的nginx配置中添加以下代码:

location / {
  try_files $uri /index.html;
}