如何从后端快速服务器获取数据到前端反应应用程序,反之亦然

问题描述

我有一个简单的 express 后端

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-app 创建的简单前端

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

import App from "./app"


ReactDOM.render(
  <div>
    <App />
  </div>,document.getElementById("root"));

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

解决方法

在您的组件中创建一个方法并使用内置的 fetch 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);
        }
      )
  }

查看here了解更多详情。

在节点端进行以下更改:

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"));

注意:如果您按照 this 文章创建带有 Node 后端的 React 应用程序会很容易。