reactjs - 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"
}
]
所以我不明白数据如何为空
提前致谢
解决方案
我相信您的后端正在期待_id
. req.body
但是,您当前没有在 axios 请求中创建此密钥。
根据文档,您需要向data
“选项”对象添加一个键:
axios.get('url', {data: {_id: [/* array of product ids */]}});
console.log(req.body)
您可以通过添加后端代码来确认这一点。
推荐阅读
- php - Symfony 分析器仅记录异常
- javascript - 单击其他输入时在输入上触发jquery函数
- sql-server - 使用 Node.JS 和 SQL Server Always Encrypted 插入数据库时出错
- angular - ng-bootstrap 的 ngbDatepicker 不起作用
- javascript - 编写单个 JS 脚本以将 ID 分配给 HTML 中的输出
- android - 无导航编辑器 - Android Studio Canary 15 和 16
- ruby-on-rails - Ruby on Rails - 为帖子添加评论
- swing - 在 JavaFX 中设置本机分辨率
- opengl - glDrawElements 不呈现来自 obj 文件的输入
- symfony - knpMenuBundle symfony 4