Req.body在node.js中不可迭代

问题描述 投票:1回答:2

我正在构建模拟restful API以便更好地学习。我正在使用MongoDB和node.js,为了测试我使用postman。

我有一个发送更新请求router.patch的路由器。在我的数据库中,我有name(字符串),price(数字)和imageProduct(字符串 - 我保持图像的路径)。

我可以在邮递员上使用原始格式更新我的nameprice对象,但我无法使用表单数据更新它。据我所知,在原始格式中,我使用数组格式更新数据。有没有办法在表单数据中执行此操作?使用表单数据的目的,我想上传一个新图像,因为我可以更新productImage的路径,但我无法上传新的图像公用文件夹。我该怎么处理?

以原始格式更新数据的示例

[ {"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
        });
    });
});
node.js mongodb rest api postman
2个回答
4
投票

使用for ...是一个好主意,但你不能像使用它来循环访问对象的属性一样。值得庆幸的是,Javascript有一些新功能可以将“对象的属性”转换为可迭代的。

使用Object.keys:

const input = {
  firstName: 'Evert',
} 
for (const key of Object.keys(input)) {
  console.log(key, input[key]);
}

您还可以使用Object.entries来键入键和值:

const input = {
  firstName: 'Evert',
} 
for (const [key, value] of Object.entries(input)) {
  console.log(key, value);
}

0
投票

要处理多部分表单数据,bodyParser.urlencoded()app.use(bodyParser.json());body解析器将不起作用。

请参阅建议的模块here以解析多部分主体。

在这种情况下,您将被要求使用multer

 var bodyParser = require('body-parser');
 var multer = require('multer');
 var upload = multer();

// for parsing application/json
app.use(bodyParser.json()); 

// for parsing application/xwww-
app.use(bodyParser.urlencoded({ extended: true })); 
//form-urlencoded

// for parsing multipart/form-data
app.use(upload.array()); 
app.use(express.static('public'));
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.