我有一个由简单的Express服务器提供服务的React应用程序。 React应用程序正在webpack
'd到我的根目录(server.js
文件所在的目录)中名为dist
的目录中。 dist文件夹包括index.html
入口点,main.min.js
JavaScript包以及所有其他静态资源(CSS,图像等)。在Express服务器上使用react-router
如果我访问该网站的根目录,例如localhost:3000/
,index.html
获得服务,它会加载JS包并找到所有其他资产。该应用程序使用react-router
,通过点击按钮进行良好导航,并且链接将我带到localhost:3000/feature
正常工作。
不过,如果我手动进入在localhost:3000/feature
地址栏和类型,服务器对预期的index.html
,而且在地方main.min.js
供应index.html
。这是因为快速服务器中的通配符路由映射为返回index.html
。这是我在某些文章中看到的,但我不确定是否考虑过这种情况。
下面是相关的服务器代码片段:
app.use(express.static(path.join(__dirname)));
app.get('*', function response(req, res) {
res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});
这是定义了服务器的路由。有没有更好的方式来做到这一点,这将允许手动更改地址?
这里是我的文件结构,如果有帮助:的index.html
|-root
|-server.js
|-webpack.config.js
|-dist/
|-main.min.js
|-index.html
|-a2cea76fae187add3c974dcacf446eab.jpg
|-...etc
内容:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="root"><!-- React app --></div>
<script src="dist/main-631cea2c7e308b1dfb26.min.js"></script>
</body>
</html>
可能需要[这](https://github.com/ReactTraining/react-router/blob/master/docs/guides/ServerRendering.md) –
@IslamIbakaev这是唯一的解决办法?如果可以,我想避免服务器端渲染(现在)。 –
我不知道其他解决方案,我希望快速匹配路由我与反应路由器设置没有实际做“服务器端反应” –