节点Js无法读取未定义的属性



我试图将多个图像从表单上传到网页,但问题是它在for循环的每一步都会创建新的条目。如果我将其从循环中取出,则req.body.ca.video1将变为未定义。如何使用所有图像只创建一次条目。

路线后

router.post("/n/v/n", upload.array('images'), middleware.isloggedin, async function(req, res) {
try {
req.body.ca.video1 = [];
for (var i = 0; i < req.files.length; i++) {
console.log(req.files[i].path);
cloudinary.v2.uploader.upload(req.files[i].path, { resource_type: "auto" },  function(error, result) {
req.body.ca.video1.push({
url: result.secure_url,
format: result.format
});
req.body.ca.author = {
id: req.user._id,
username: req.user.username
}
req.body.ca.created = new Date();
////if i get out of this then req.body.ca becomes undefined
const campground = await Campground.create(req.body.ca);
});
/////here the video1 goes undefined
}
req.flash("success", "it is uploading");
res.redirect("/c");
} catch (err) {
req.flash("error", err.message);
res.redirect("back");
}
});

这是因为cloudinary.upload是异步的。在请求结束之前执行循环外。

您需要等待请求完成才能访问它。

此外,您不应该在请求主体上声明新的变量,除非您在管道上的另一个中间件上需要它们。

最新更新