簡體   English   中英

從節點 js 傳遞數據以響應 js

[英]passing data from node js to react js

我正在嘗試從節點傳遞數據以做出反應,但完美地以文本形式(如res.text()獲取數據,但無法以 object 形式獲取數據。 也嘗試使用 map 進行渲染,但無法正常工作。

反應 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();
});
   

首先,您沒有在 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 端,獲取 API 是一個很好的做法,結果是 componentDidMount function 而不是 componentWillMount。 如果 API 響應是數組/對象類型,那么如果您只想在 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>
    )
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM