如何使用expressJS提供ReactJS静态文件?

22

问题

我已经成功地提供了我的React应用程序的index.html文件,但是替换html文件中的<root>的 index.js 却无法在 ReactDOM.render 上触发。我该如何启动 index.js 文件呢? 如果我对提供 React 应用程序的方式有任何误解,我会非常感激您的澄清。

文件结构

  • / - 包含所有服务器端文件,包括server.js
  • /client/ - 包含所有React文件
  • /client/build/ - 包含所有准备好的生产客户端文件
    • /client/build/index.html
    • /client/build/static/js/main.[hash].js - 似乎是包含我的React应用程序的ReactDOM.render的 index.js 的缩小版本。

当前部署

  • 我正在使用Facebook的create-react-app为/client/目录,包括npm run build以自动填充/client/build/

文件片段

// server.js
let app = express();
app.use(express.static(path.join(__dirname, '../client/public')));

这成功加载了由create-react-app提供的默认index.html

// index.html
<body>
  <noscript>
    You need to enable JavaScript to run this app.
  </noscript>
  <div id="root"></div>
</body>

上面的代码段可能有用,也可能无用,但它是随 create-react-app 一起提供的默认 html 文件。我需要用引用被压缩过的 index.js 文件的 script 标签来替换 noscript 标签吗?我尝试过这样做,但没有任何变化,也许是因为相对路径设置不正确。


这个代码示例可能会有所帮助,欢迎留下评论。https://github.com/mInzamamMalik/Serving-ReactJS-web-application-in-express.js-static-file-hosting - Inzamam Malik
4个回答

32
试错后尝试了许多不同的方法,解决方案非常简单:
在静态调用中提供/client/build文件夹的服务,如下所示:
app.use(express.static(path.join(__dirname, '../client/build')));

你能解释一下为什么这个可以工作吗?因为如果你看一下你的文件夹结构,可能没有client/build文件夹。 - mirsahib
2
只有在使用 npm run build 构建客户端站点后才能正常运行。您需要提供由 React 生成的客户端代码,而不是您正在工作的 public 文件夹。 - Kubo2
如何获取“/”路径 - Darshan

3

我有一段时间也遇到了同样的问题,现在我可以说解决方案分为两部分以避免路由器问题:

  1. 从CRA构建中提供静态文件(在你的情况中是client / build)
const buildPath = path.normalize(path.join(__dirname, '../client/build'));
app.use(express.static(buildPath));
  1. 在服务器中所有其他路由器之后设置最终路由,使用以下内容:
const rootRouter = express.Router();
/* 
* all your other routes go here
*/
rootRouter.get('(/*)?', async (req, res, next) => {
  res.sendFile(path.join(buildPath, 'index.html'));
});
app.use(rootRouter);

0
我的项目结构
项目
-->客户端
后端(express)
使用 npm run build 后,我发现 build 中的 index.html 使用了错误的 css 文件或静态文件目录。

const path = require('path');
app.use(express.static(path.join(__dirname, '/client/build/')));

i know i also tried ../client...... but not working

so what i did is cut and paste static folder of build in root directory this image can give you the idea, and its working structure


0

//在你的React应用程序中运行

npm run build

//请在您的服务器上插入以下代码

const path = require("path");
app.use(express.static(path.join(__dirname,"nameOfYourReactApp","build")))

//Replace nameOfYourReactApp with the name of your app

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接