首页 > 解决方案 > 如何从后端快速服务器获取数据到前端反应应用程序,反之亦然

问题描述

我有一个简单的快递后端

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

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

标签: node.jsreactjsexpressmernweb-development-server

解决方案


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

在这里查看更多详情。

在节点端进行以下更改:

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

注意:如果你按照这篇文章创建一个带有 Node 后端的 React 应用程序将会很容易。


推荐阅读