首页 > 解决方案 > axios.get 在数据中返回空数组

问题描述

我正在尝试使用 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) 时,它返回 数据: Array(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"
}
]

所以我不明白数据如何为空

提前致谢

标签: reactjsaxiosmongodb-query

解决方案


我相信您的后端正在期待_id. req.body但是,您当前没有在 axios 请求中创建此密钥。

根据文档,您需要向data“选项”对象添加一个键:

axios.get('url', {data: {_id: [/* array of product ids */]}});

console.log(req.body)您可以通过添加后端代码来确认这一点。


推荐阅读