简体   繁体   中英

Node Js cannot read property of undefined

i am trying to upload multiple images from a form to a webpage but the problem is that it is creating new entries at each step of the for loop if i take it out of the loop then the req.body.ca.video1 becomes undefined. how do i create the entry only one time with all the images.

the post route

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");
    }

});

That's because cloudinary.upload is async. Outside of the loop is executed before the request ends.

You need to wait for the request to finish to be able to access it.

Also you shouldn't declare new variables on the request body, unless you need them on another middleware on the pipeline.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM