【发布时间】:2020-01-21 03:04:11
【问题描述】:
我被困在我的 GET Route 端点上,将一个 JSON 数据数组从 MongoDB 返回到我的 localhost:5000 服务器,因此我可以为我的前端检索它 axios。到目前为止,我的代码只有控制台在 Visual Studio Code 中的服务器终端上使用前端所需的数据注销文档
这是 GET 路由的服务器代码
app.get('/pets', function(req, res){
const resultArray = [];
client.connect(err => {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
const cursor = db.collection('pet').find({});
iterateFunc = (doc,err) => {
assert.equal(null, err);
resultArray.push(doc);
console.log(JSON.stringify(doc, null, 4));
if(err) {
console.log(err)
}
}
cursor.forEach(iterateFunc);
client.close();
res.send({pets: resultArray});
});
这是获取路由的前端 Reactjs 代码
import React, {
Component
}
from 'react';
import axios from 'axios';
export default class ListPets extends Component {
constructor(props) {
super(props);
this.state = {
pets: [],
isLoaded: false,
}
}
componentDidMount = () => {
this.getPets();
};
getPets = async() => {
const res = await axios.get('http://localhost:5000/pets/');
const pets = res.data;
this.setState({
isLoaded: true,
pets: pets
});
console.log('Data has been received!');
console.log(pets.data)
return pets;
}
render() {
console.log('State: ', this.state);
const {
isLoaded,
} = this.state;
if (!isLoaded) {
return <div> Loading... </div>;
} else {
return (<div></div>);
}
}
}
【问题讨论】:
-
前端的数据是什么样的? ,我认为,由于数据已正确记录在服务器上(在对其进行字符串化之后),请尝试在 find() 之后调用
toArray(),如下所示:db.collection('pet').find({}).toArray()跨度> -
在浏览器控制台pets中是一个空数组:[ ]
-
嗨Joshua Lipscomb,你对我的回答不满意吗?你检查过提供的沙箱吗?让我知道有什么问题可以进一步帮助您