【问题标题】:Express server serving index.html instead of chunk files, in a React app在 React 应用程序中服务 index.html 而不是块文件的 Express 服务器
【发布时间】:2021-09-03 17:50:07
【问题描述】:

我正在尝试提供一个使用 create-react-app 启动的 React 应用程序(Typescript)的生产版本。

我正在关注官方指南:https://create-react-app.dev/docs/deployment/

我的设置没有什么独特之处。这是 server.js 文件,位于根目录(src 上方):

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


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

生产文件在名为 build 的文件夹中创建。生成的路径示例:

  <script src="./static/js/main.0ae46692.chunk.js"></script>

当我导航到 localhost:8000/ 时,一切正常。初始请求提供 index.html,脚本请求提供正确的文件。

但是,当我尝试(从浏览器)导航到类似 localhost:8000/todos 的内容时,所有脚本请求都返回 index.html。

我没有看到我的设置有什么“特别”之处,也不明白发生了什么。我在指南中遗漏了什么吗?它明确指出app.get('/*',...) 解决了这个问题。

任何帮助将不胜感激。

【问题讨论】:

  • 这听起来像问题是脚本标签是用relative paths 生成的,因为它在您向根 / 发出请求时起作用,但不是其他任何东西。您可以尝试将“主页”设置为“localhost:8000”吗?
  • 嗯,成功了。另外,当我做主页:“/”时,它工作正常。谢谢。

标签: node.js reactjs


【解决方案1】:

将评论复制到此处的答案中,以便对其进行标记。

这听起来像问题是脚本标签是用relative paths 生成的,因为它在您向根 / 发出请求时起作用,但不是其他任何东西。您可以尝试将“主页”设置为“localhost:8000”

【讨论】:

    猜你喜欢
    • 2020-03-14
    • 1970-01-01
    • 2017-03-31
    • 1970-01-01
    • 2016-09-30
    • 1970-01-01
    • 1970-01-01
    • 2019-03-07
    • 2020-05-05
    相关资源
    最近更新 更多