【问题标题】:How to get data from backend express server to frontend react app and vice versa如何从后端快速服务器获取数据到前端反应应用程序,反之亦然
【发布时间】:2021-07-26 11:49:03
【问题描述】:

我有一个简单的 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"));

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

【问题讨论】:

    标签: node.js reactjs express mern web-development-server


    【解决方案1】:

    在您的组件中创建一个方法并使用内置的 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 应用程序会很容易。

    【讨论】:

      猜你喜欢
      • 2021-06-11
      • 1970-01-01
      • 1970-01-01
      • 2015-01-02
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 2013-01-20
      • 1970-01-01
      相关资源
      最近更新 更多