Node.js 如何将数据从后端express服务器获取到前端react应用程序,反之亦然

Node.js 如何将数据从后端express服务器获取到前端react应用程序,反之亦然,node.js,reactjs,express,mern,web-development-server,Node.js,Reactjs,Express,Mern,Web Development Server,我有一个简单的后端快递 const express = require("express"); const app = express(); var array = [1,2,3,4,5] app.get("/", function(req, res){ res.send("this is backend of application"); }) app.listen(5000, ()=> console.log(&q

我有一个简单的后端快递

const express = require("express");

const app = express();

var array = [1,2,3,4,5]

app.get("/", function(req, res){
  res.send("this is backend of application");
})

app.listen(5000, ()=> console.log("listening on 5000"));
我还有一个由create-react应用程序创建的简单前端

import React from "react";
import ReactDOM from "react-dom";

import App from "./app"


ReactDOM.render(
  <div>
    <App />
  </div>, document.getElementById("root"));
从“React”导入React;
从“react dom”导入react dom;
从“/App”导入应用程序
ReactDOM.render(
,document.getElementById(“根”);

现在,我的问题是如何将“数组”从后端文件获取到前端文件,并进行响应。反之亦然???

在组件中创建一个方法并使用内置的获取API。您也可以使用
axios

componentDidMount() {
    fetch("http://localhost:5000/")
      .then(res => res.json())
      .then(
        (result) => {
          // set state here
          console.log(result);
        },
        // Note: it's important to handle errors here
        // instead of a catch() block so that we don't swallow
        // exceptions from actual bugs in components.
        (error) => {
          console.log(error);
        }
      )
  }
查看更多详细信息

在节点端进行以下更改:

const express = require("express");

const app = express();

var array = [1,2,3,4,5]

app.get("/", function(req, res){
  res.send({message: "this is backend of application", data: array});
})

app.listen(5000, ()=> console.log("listening on 5000"));
注意:若您按照本文创建一个带有节点后端的React应用程序,那个么这将很容易