简体   繁体   English

将 Node.js 后端添加到 React 项目?

[英]Add Node.js backend to React project?

So I have created a React app with所以我创建了一个 React 应用程序

npx create-react-app my-app

and written a few functions and some content to my web app.并为我的 web 应用程序编写了一些功能和一些内容。 Now I do need to implement backend for connecting to my SQL database and reading/writing from there.现在我确实需要实现后端以连接到我的 SQL 数据库并从那里读/写。 It is my understanding that server-side logic (NodeJS) and front-end code (React) should be in same repository, but how exactly is that done?我的理解是服务器端逻辑(NodeJS)和前端代码(React)应该在同一个存储库中,但是具体是怎么做的呢? I should probably create /backend folder and server.js inside it, but where?我可能应该在其中创建/backend文件夹和server.js ,但是在哪里? In the same folder with node_modules , public and src or elsewhere?在与node_modulespublicsrc或其他地方相同的文件夹中? Also, it would be nice to know more about how information exchange between Node and React works so I can display data fetched from database with React.此外,很高兴了解更多关于 Node 和 React 之间的信息交换如何工作的信息,这样我就可以使用 React 显示从数据库中获取的数据。 Thanks in advance.提前致谢。

For development I have two folders on same level - src with react and server with node.对于开发,我在同一级别上有两个文件夹 - 带有 react 的src和带有节点的server You start (eg)你开始(例如)

  • nodejs server on port 5000 5000端口上的nodejs服务器
  • webpack-dev-server on port 3000端口 3000 上的 webpack-dev-server

React communicates with backend via REST API. React 通过 REST API 与后端通信。 You have to proxy api requests to your server (part of webpack dev configuration):您必须将 api 请求代理到您的服务器(webpack 开发配置的一部分):

devServer: {
    contentBase: path.join(__dirname, 'server', 'static', 'public'),
    port: 3000,
    publicPath: 'http://localhost:3000/',
    historyApiFallback: true,
    disableHostCheck: true,
    hot: true,
    proxy: {
      '/api': {
        target: 'http://127.0.0.1:5000/',
      },
    },
  },

In production environment the react is compiled to server/reactapp subfolder and served with expressjs as any other webpage.在生产环境中,react 被编译到server/reactapp子文件夹,并与 expressjs 一起作为任何其他网页提供服务。

Part of webpack production: webpack生产部分:

output: {
    path: path.join(__dirname, 'server', 'reactapp'),
    // publicPath: path.join('dist'),
    filename: '[name].bundle.js',
    publicPath: '/',
  },

In Express (or any other web framework) you then serve the /api path with your backend tasks.然后,在 Express(或任何其他 web 框架)中,您可以为后端任务提供 /api 路径。

This all means I have two separated development environments - server and react, which partly join till in production environment.这一切都意味着我有两个独立的开发环境——服务器和反应,它们部分加入到生产环境中。 They both have separated package.json and node_modules.它们都分离了 package.json 和 node_modules。 In newer versions I have replaced REST API communication with websocket, what needs some other settings in communication.在较新的版本中,我已将 REST API 通信替换为 websocket,在通信中需要一些其他设置。

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM