【发布时间】:2021-06-22 09:03:04
【问题描述】:
我正在尝试使用 mongo 在 react js 中实现购物车 这是前端请求
useEffect(() => {
if(state === null) {
setLogin(false)
}
else {
setLogin(true)
if(state.cart !== null) {
axios.get('http://localhost:5000/cart',state.cart)
.then(res => {
console.log("res data is : " , res );
})
}
state.cart 是来自令牌的产品 ID 数组,然后用于在后端获取产品文档。
这是后端路由代码:
router.route('/cart').get((req,res) => {
const pids = req.body._id
Product.find({"_id" : { $in : pids}}, function(err, result){
if(err){
res.send(err)
}
else{
// console.log(result)
res.json(result)
}
})
})
当我在 axios 中使用 console.log(res) 时,它会返回 数据:数组(0),状态:200,状态文本:“OK”,标题:{...},配置:{...},...}
这里的数据数组是空的,但 Insomnia 给了我一个像这样的正确数组:
[
{
"_id": "60c7566b5e9943a056f83af2",
"id": 1,
"name": "Coffee",
"description": "This coffee uses both Robusta and Arabica beans. A delicacy for
connoisseurs.",
"cost": 10,
"img": "img/coffee.jpg"
},
{
"_id": "60c7578a5e9943a056f83af3",
"id": 2,
"name": "Muffin",
"description": "A muffin nom nom :)",
"cost": 2,
"img": "img/muffin.png"
},
{
"_id": "60c757bf5e9943a056f83af4",
"id": 3,
"name": "Biscuit",
"description": "The best chocolate sandwich biscuit in town.",
"cost": 4,
"img": "img/biscuit.jpg"
}
]
所以我不明白数据怎么是空的
提前致谢
【问题讨论】:
标签: reactjs axios mongodb-query