【问题标题】:Having some trouble deploying react app and express/node.js backend on same port在同一端口上部署 react 应用程序和 express/node.js 后端时遇到一些问题
【发布时间】:2020-09-04 15:58:26
【问题描述】:

我想在 localhost:5000 上为我的 react 前端提供服务,api 请求将转到 localhost:5000/api/some-path。

我已经看到了一些类似的问题,并且根据我的理解:

  • 在 package.json 中添加代理

  • 从构建文件夹提供静态文件

package.json 的相关部分:

  "proxy" : "http://localhost:5000",
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

server.js 的相关部分:

const PORT = 5000 || process.env.port;
app.use(express.static(path.join(__dirname, 'build')));

app.get('/', function(req,res) {
  res.sendFile(path.join(__dirname, '../public', 'index.html'));
});

生产命令:

$ npm run build
$ serve -s build

问题在于,每个获取请求的响应都是 index.html 文件。

请注意,在开发版本中,一切正常。我从端口 3000 开始响应应用程序,请求将发送到 localhost:5000/api/path 以响应 json 数据。

【问题讨论】:

    标签: javascript node.js reactjs express deployment


    【解决方案1】:

    问题出在这一行:app.use(express.static(path.join(__dirname, 'build'))); 构建文件夹位于包含文件 server.js 的文件夹之外。 更正为:app.use(express.static(path.join(__dirname, '../build')));

    【讨论】:

      【解决方案2】:

      作为一个刚接触代码的人,我最近很难部署 react 和 node。我最终是如何做到的:

      1. 使用 npm run build 构建 react 应用
      2. 复制node.js项目根目录下的build文件夹
      3. 在 index 或 app.js 中包含此代码
      app.use(express.static(path.join(__dirname, 'build')));
      
      app.get('/', function(req,res) {
        res.sendFile(path.join(__dirname, 'build', 'index.html'));
      });
      
      const PORT = 5000 || process.env.port;
      app.listen(PORT, ()=> console.log(`Listening on port ${PORT}...`));
      
      1. 使用 node index.js 或 node app.js 启动应用程序,就是这样

      【讨论】:

        猜你喜欢
        • 2021-08-01
        • 2021-04-21
        • 2020-07-14
        • 1970-01-01
        • 1970-01-01
        • 2015-04-28
        • 2020-03-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多