reactjs - 捆绑 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 文件中设置一些东西,我的应用程序是否捆绑用于生产?
解决方案
如果 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.html
React 客户端/前端应用程序的位置。确切的内容sendFile()
完全取决于您的项目结构。例如,如果您将 React 应用程序放在名为create-react-app的文件夹中,client
则该build
文件夹如下所示: npm run build
sendFile()
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 应用程序。
希望这会有所帮助!
推荐阅读
- aws-sdk - 无法使用 aws-sdk 访问 aws 资源,但能够使用 aws cli 和 Web 控制台访问
- java - 该系统找不到指定的路径。'-Xmx1000M' 不是内部或外部命令、可运行程序或批处理文件
- python - 如何在pyspark中进行矩阵乘法?
- c++ - 如何在计算答案到达变量之前停止循环?
- .net-core - 实体框架导航属性自定义命名
- node.js - Node.js server.listening 标志始终为 false
- java - 我的应用程序的命令行参数是什么?
- excel - Excel - 查找和替换字符
- angular - 在角度日期选择器中重置当前日期选择
- laravel - 在 laravel 的 hichart 中显示了图表的坐标页面但是数据没有显示为图表