首页 > 解决方案 > 捆绑 React/Express 应用程序进行生产

问题描述

我的应用程序是用“create-react-app”和 Express.js 作为后端构建的。我应该如何设置应用程序以进行生产?

这是我来自 Express 的 user.js 文件:

var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.json(['Hello World'])
});

module.exports = router;

我在 React 文件夹的 package.json 文件中有“代理”设置。

"proxy": "http://localhost:3001"

“create-react-app”有构建命令:

npm run build

如果我只是在 react 文件夹中运行“npm run build”或者我必须在我的 Express 文件中设置一些东西,我的应用程序是否捆绑用于生产?

标签: reactjsexpressproduction

解决方案


如果 Express 同时充当您的 API 和应用程序服务器,则在基本级别上,您需要设置 Express 以index.html在没有捕获其他 API 路由时加载 React 应用程序。您可以通过sendFile()与 Node 一起使用,在您的 Express 应用程序的主文件中注册所有其他 API 端点之后path的“catch-all”路由来做到这一点。

app.use('/users', usersRouter);

app.use('*', function (request, response) {
  response.sendFile(path.resolve(__dirname, 'index.html'));
});

其中的路径sendFile()需要指向index.htmlReact 客户端/前端应用程序的位置。确切的内容sendFile()完全取决于您的项目结构。例如,如果您将 React 应用程序放在名为create-react-app的文件夹中,client则该build文件夹如下所示: npm run buildsendFile()

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

// API route
app.use('/users', usersRouter);

app.use('*', function (request, response) {
  response.sendFile(path.join(__dirname, 'client', 'build', 'index.html'));
});

*in app.use()such表示所有app.use('*', function (request, response));HTTP 动词(GET、POST、PUT 等)。如果你没有把它放在的 API 路由/路径之后,它将阻止你的 React 客户端应用程序调用 API,因为它会捕获所有请求,顺序非常重要。

然后,您只需构建 React 应用程序,然后运行 ​​Express 应用程序。

希望这会有所帮助!


推荐阅读