在Express服务器上使用react-router

我有一个简单的Express服务器正在服务的React应用程序。 React应用程序正在被webpack放到我的根目录( server.js文件所在的位置)的一个名为dist目录中。 dist文件夹包括index.html入口点, main.min.js JavaScript包以及所有其他静态资源(css,图像等)。

如果我访问该站点的根目录localhost:3000/例如, index.html得到服务,它加载JS捆绑并发现所有其他资产罚款。 该应用程序,使用react-router ,通过button点击和一个链接,使我到localhost:3000/feature正常工作正常导航。

但是,如果手动进入地址栏并键入localhost:3000/feature ,则服务器会按照预期提供index.html ,但也会用index.html代替main.min.js 这是因为快速服务器中的通配符路由被映射为返回index.html 。 这是我在一些文章中看到的,但是我不确定这个案子是否被考虑过。

以下是相关服务器代码的一部分:

 app.use(express.static(path.join(__dirname))); app.get('*', function response(req, res) { res.sendFile(path.join(__dirname, 'dist', 'index.html')); }); 

这是什么定义服务器路由。 有没有更好的方法来做到这一点,将允许手动地址更改?

这是我的文件结构,如果有帮助:

 |-root |-server.js |-webpack.config.js |-dist/ |-main.min.js |-index.html |-a2cea76fae187add3c974dcacf446eab.jpg |-...etc 

index.html内容:

 <!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> 

这是因为你正在使用相对path来引用你的脚本。

例如,当http://localhost:3000/feature浏览器将脚本parsing为http://localhost:3000/feature/dist/main-631cea2c7e308b1dfb26.min.js这当然不存在,因此express.static中间件正在让请求落到下一个中​​间件。

因此,您需要将其定义为根相对path,例如

 <script src="/dist/main-631cea2c7e308b1dfb26.min.js"></script>