【发布时间】: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