Req.body 在 node.js 中不可迭代 [英] Req.body is not iterable in node.js
问题描述
我正在构建模拟 Restful API 以更好地学习.我正在使用 MongoDB 和 node.js,为了测试,我使用邮递员.
I am building mock restful API to learn better. I am using MongoDB and node.js, and for testing I use postman.
我有一个发送更新请求的路由器router.patch
.在我的数据库中,我有 name
(字符串)、price
(数字)和 imageProduct
(字符串 - 我保存图像的路径).
I have a router that sends update request router.patch
. In my DB, I have name
(string), price
(number) and imageProduct
(string - I hold the path of the image).
我可以在邮递员上使用 raw-format 更新我的 name
和 price
对象,但我无法使用 form 更新它-数据.据我了解,在 raw-form 中,我使用数组格式更新数据.有没有办法在 form-data 中做到这一点?使用form-data的目的,我想上传一张新的图片,因为我可以更新productImage
的路径,但是我不能上传一个新的图片公共文件夹.我该如何处理?
I can update my name
and price
objects using raw-format on the postman, but I cannot update it with form-data. As I understand, in raw-form, I update the data using the array format. Is there a way to do it in form-data? The purpose of using form-data, I want to upload a new image because I can update the path of productImage
, but I cannot upload a new image public folder. How can I handle it?
以原始形式更新数据的示例
[ {"propName": "name"}, {"value": "test"}]
router.patch
router.patch('/:productId', checkAuth, (req, res, next) => {
const id = req.params.productId;
const updateOps = {};
for (const ops of req.body) {
updateOps[ops.propName] = ops.value;
}
Product.updateMany({_id: id}, {$set: updateOps})
.exec()
.then(result => {
res.status(200).json({
message: 'Product Updated',
request: {
type: 'GET',
url: 'http://localhost:3000/products/' + id
}
});
})
.catch(err => {
console.log(err);
res.status(500).json({
err: err
});
});
});
推荐答案
使用 for...of 是一个好主意,但您不能像使用它那样循环遍历对象的属性.幸运的是,Javascript 有一些新函数可以将对象的属性"转换为可迭代对象.
Using for...of is a great idea, but you can't use it like you are to loop through an object's properties. Thankfully, Javascript has a few new functions that turn 'an object's properties' into an iterable.
使用Object.keys:
const input = {
firstName: 'Evert',
}
for (const key of Object.keys(input)) {
console.log(key, input[key]);
}
您还可以使用 Object.entries 来键入键和值:
You can also use Object.entries to key both the keys and values:
const input = {
firstName: 'Evert',
}
for (const [key, value] of Object.entries(input)) {
console.log(key, value);
}
这篇关于Req.body 在 node.js 中不可迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!