React.js 构建环境不显示根路由的其他路由

React.js build enviroment doesn't show other routes thant the root one

当 运行 来自构建版本时,我无法访问我在我的应用程序中设置的路由。尽管当我的 React 应用程序运行在与服务器不同的端口时,我可以在开发环境中访问它们。

我在我的快速服务器中包含了以下内容,以便它为 React 应用程序提供服务,并且只显示根页面。

app.use(express.static(path.join(__dirname, 'build')))

app.get('/', function (req, res) {
  res.sendFile(path.join(__dirname, 'build', 'index.html'))
})

React Router 在浏览器中完成所有路由,因此您需要确保将每个路由的 index.html 文件发送给您的用户。

这应该是您所需要的:

app.use('/static', express.static(path.join(__dirname, '../client/build//static')));
app.get('*', function(req, res) {
  res.sendFile('index.html', {root: path.join(__dirname, '../../client/build/')});
});

我找到了问题的解决方案。

我在代码中使用 HTML 锚标记而不是 react-router 的 Link 属性。 相应地更换了它们,我的应用程序运行正常。