【发布时间】:2021-05-28 01:25:01
【问题描述】:
我正在构建一个 MERN Web 应用程序,但我遇到了一个错误,即当我在 clinet 端发出 get 请求时,我没有从服务器获取正确的数据。
这是来自服务器的控制器函数,用于请求 GET http://localhost:5000/public_facility/:id
export const getPublicFacilityData = async (req, res) => {
const { id } = req.params;
if(!mongoose.Types.ObjectId.isValid(id)){
return res.status(404).json({ message: `No valid public facility id: ${id}`});
}
try {
const result = await PublicFacilityModel.findById(id, 'name data');
res.status(200).json({result});
} catch (error) {
res.status(500).json({ message: 'Could not get public facility data'});
console.log(error);
}
}
这是我使用带有示例 id 的邮递员或 VS REST 客户端扩展获得的结果(与我在 MongoDB 中的数据相同):
"result": {
"_id": "60269642b8f3741a7c6a54ei",
"name": "TOWN HALL",
"data": [
{
"year": 2019,
"annual_data": [
{
"consumption": [10,10,10]
"price": [],
"concept": "Total"
},
{
"consumption": [20,20,20],
"price": [],
"concept": "Electricity"
}
]
},
{
"year": 2018,
"annual_data": [
{
"consumption": [30,30,30],
"price": [],
"concept": "Total"
}
]
}
]
}
}
这是我从客户端发出请求的函数:
export const getPublicFacilityDatasets = async (id) => {
if(id){
try {
const res = await axios.get(`http://localhost:5000/public_facility/${id}`);
//console.log('Result: ', res.data);
//console.log('Total consumption 2018', res.data.result.data[1].annual_data[0].consumption);
...
} catch (error) {
...
}
}
}
这是我在客户端执行请求时收到的数据:
{
"result": {
"_id": "60269642b8f3741a7c6a54ei",
"name": "TOWN HALL",
"data": [
{
"year": 2019,
"annual_data": [
{
"consumption": [10,10,10]
"price": [],
"concept": "Total"
},
{
"consumption": [20,20,20],
"price": [],
"concept": "Electricity"
}
]
},
{
"year": 2018,
"annual_data": [
{
"consumption": [10,10,10],
"price": [],
"concept": "Total"
}
]
}
]
}
}
它看起来与我数据库中的数据相同,但 2018 年的总消费量 (result.data[1].annual_data[0].consumption) 具有 2019 年的总消费量值。
我发现很奇怪,如果我在请求之前执行console.log(res.data),res.data.result.data[1].annual_data[0].consumption 的值是错误的[10,10,10],但如果我执行console.log(res.data.result.data[1].annual_data[0].consumption),它会显示正确的值[30,30,30]。看起来它们不是同一个对象,但我没有任何其他名为 result 的变量。
有人有什么想法吗?如果我需要提供更多详细信息,请告诉我。
【问题讨论】:
标签: javascript node.js json reactjs mern