【问题标题】:passing data from node js to react js从节点 js 传递数据到反应 js
【发布时间】:2022-02-03 17:58:30
【问题描述】:

我正在尝试从节点传递数据以做出反应,但以文本形式获取数据,如 res.text() 完美但无法以对象形式获取数据。 也尝试过使用地图进行渲染,但无法正常工作。

反应 JS

import React, { Component } from 'react'
import axios from 'axios';
export default class List extends Component {
  constructor(props)
  {
    super(props);
    this.state={apiResponse:[]};
    
  }
callAPI()
  {
    fetch("http://localhost:9000/testAPI")
    .then( (res) => res.json())   
    .then( (json) => {this.setState({apiResponse: json});});
  }

  componentWillMount()
  {
    this.callAPI();
  }

  render() {
    return (
      <div>
        <h1>{this.state.apiResponse}</h1>
      </div>
    )
  }
}

节点 JS

router.get("/", function (req, res) {
  MongoClient.connect(url, function (err, db) {
    if (err) throw err;
    var dbo = db.db("to-do");
    // var query = { address: "Park Lane 38" };
    dbo
      .collection("to-do")
      .find({})
      .toArray(function (err, result) {
        if (err) throw err;
        console.log(result);
        // res.send((result))
        db.close();
      });
  });
  // console.log();
});
   

【问题讨论】:

  • 快到了:res.json(result)
  • 错误:对象作为 React 子项无效(发现:对象的键为 {_id、task、user、dueDate、startDate、complete})。如果您打算渲染一组子项,请改用数组。
  • 收到此错误。
  • 啊,我不知道,这是下一个问题。当前的问题是“如何将数据从 Node 发送到 React”,这就是方法。现在,如果您对 React 有其他问题,您应该提出另一个问题

标签: javascript node.js reactjs express


【解决方案1】:

首先你没有在 NodeJS Get Request 中发送响应

router.get("/", function (req, res) {
  MongoClient.connect(url, function (err, db) {
  if (err) throw err;
  var dbo = db.db("to-do");
  // var query = { address: "Park Lane 38" };
  dbo
   .collection("to-do")
   .find({})
   .toArray(function (err, result) {
     if (err) throw err;
     res.send((result))
     db.close();
   });
});

});

然后在 React 端,使用 componentDidMount 函数而不是 componentWillMount 获取 API 结果是一个很好的做法。 如果 API Response 是数组/对象类型,那么如果您只想在 React 中显示结果,请使用 JSON.stringify(object) ,例如:

import React, { Component } from 'react'
import axios from 'axios';
export default class List extends Component {
  constructor(props)
  {
    super(props);
    this.state={apiResponse:[]};
    
  }
callAPI()
  {
    fetch("http://localhost:9000/testAPI")
    .then( (res) => res.json())   
    .then( (json) => {this.setState({apiResponse: json});});
  }

  componentWillMount()
  {
    this.callAPI();
  }

  render() {
    return (
      <div>
    <h1>{JSON.stringify(this.state.apiResponse)}</h1>
      </div>
    )
  }
}

【讨论】:

    猜你喜欢
    • 2017-07-23
    • 1970-01-01
    • 2017-02-20
    • 2020-09-14
    • 2021-07-07
    • 2021-04-25
    • 1970-01-01
    • 2018-10-15
    • 1970-01-01
    相关资源
    最近更新 更多