node.js - 如何同时运行客户端和服务器代码
问题描述
我有客户端代码,它位于客户端文件夹中。我已经完成了纱线构建来创建生产构建。
我还有一个保存 API 端点的服务器,我如何使用客户端代码的生产同时运行它们。
服务器包.json:
"scripts": {
"client-install": "npm install --prefix client",
"start": "node server.js",
"server": "nodemon server.js",
"client": "npm start --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\"",
"prod": "NODE_ENV=production concurrently \"npm run server\" \"npm run client\""
},
server.js:
// Routes
app.use("/api/users", users);
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server up and running on port ${PORT} !`));
客户端包.json:
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"proxy": "http://localhost:5000",
解决方案
当您yarn build
为客户端产品执行此操作时,您会使用 js 生成一些 index.html,比如说在 client/build 文件夹中(您可以根据需要调整路径)。因此你不需要npm run client
,你只需要提供 html 文件。server.js
可以在定义所有路由之后添加处理程序,如下所示
if (['production'].includes(process.env.NODE_ENV)) {
app.use(express.static('client/build'));
const path = require('path');
app.get('*', (req, res) => {
res.sendFile(path.resolve('client', 'build', 'index.html'));
});
}
最后一步是package.json
通过以下方式更新文件中的脚本
"prod": "NODE_ENV=production node server.js"
就是这样
推荐阅读
- excel - 如何用公式定义数字数组
- python - 无法更改一列中的分类数据(熊猫、机器学习)
- spring-boot - 如何正确模块化应用程序配置,以便测试(IT、datajpa、...)不会获取所有用于生产的内容
- r - 有没有办法在 R(或 ml3)的 recipes 包中对行(尤其是虚拟变量)进行分组
- powerbi - DAX 中的 IF 条件是在行上创建笛卡尔连接
- windows - 在 AD 中将组从一个用户复制到另一个用户,但一个特定组除外
- java - 如何从我的 Application 类中找出 onActivityResult 的结果?
- sas - 在sas中将16位帐号从char转换为数字
- java - Java - 实现 compareTo() ArrayList 自定义对象
- php - 即使不满足 $args,WP Query 也会返回结果?