首页 > 解决方案 > 如何同时运行客户端和服务器代码

问题描述

我有客户端代码,它位于客户端文件夹中。我已经完成了纱线构建来创建生产构建。

我还有一个保存 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",

标签: node.jsreactjs

解决方案


当您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"

就是这样


推荐阅读