首页 文章

使用 react-router 与 Express 服务器

提问于
浏览
2

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

如果我访问网站的根目录,例如localhost:3000/index.html得到服务,它会加载 JS 包并找到所有其他资产。该应用程序,使用react-router,通过按钮点击导航很好,一个链接,让我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>

1 回答

  • 2

    这是因为您使用相对路径引用脚本。

    例如,当http://localhost:3000/feature时,浏览器会将脚本解析为http://localhost:3000/feature/dist/main-631cea2c7e308b1dfb26.min.js,当然不存在,因此express.static中间件让请求进入下一个中间件。

    因此,您需要将其定义为根相对路径,e.g.

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

相关问题