【问题标题】:axios.get returns empty array in dataaxios.get 在数据中返回空数组
【发布时间】: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


    【解决方案1】:

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

    根据documentation,您需要在“选项”对象中添加data键:

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

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

    【讨论】:

    • 这对它没有影响
    • console.log 揭示了什么?
    猜你喜欢
    • 2020-02-15
    • 2021-12-13
    • 2020-04-11
    • 2019-12-16
    • 2021-06-30
    • 2022-11-27
    • 2023-03-10
    • 2018-05-16
    • 1970-01-01
    相关资源
    最近更新 更多