首页 > 解决方案 > 如何将 React 应用程序和 Nodejs 后端部署在子域的同一目录中?

问题描述

我有一个 React 应用程序,我用 Node js 制作了后端,也是 MongoDB 的服务器。它是一个 MERN 堆栈。我有一个目录结构,如:

-client  // this is where react app, in build version is in client/build
-middleware
-models
-routes
package.json
server.js
...

我想在我的 Filezilla 中像这样部署它:

-test.Server22c
      -backend // this is where all nodejs files
      -static    //these folder and other files are my build files in react app client/build
      -index.html
      ...

我怎样才能安排在同一个文件夹中一起工作?我在我的 react redux 中更改了我的 Axios 帖子链接中的端点,但它不起作用

标签: node.jsreactjsdeploymentweb-deploymentfilezilla

解决方案


最好的选择是使用2 个不同的端口,一个用于您的 react 应用程序,一个用于您的 node.js 服务器。

假设我们将使用:

反应

要部署 React,您可以简单地使用serve,您可以在https://create-react-app.dev/docs/deployment/找到所需的一切。

你基本上需要在你的 react 目录中执行这些命令。

npm install -g serve
serve -s build -l 80

确保您的机器上没有运行任何 apache 服务器,否则端口 80 将被占用。

节点.js

你只需要在端口 8080 上运行你的服务器,我真的不知道你使用的是哪个框架,所以假设你使用的是 express,它在你的入口点看起来像这样index.js

app.listen(8080, function() {
    console.log("Server is running on port 8080...");
});

推荐阅读