Nodejs Express : Cannot Read Property ‘image’ of Null and Unhandled Error Event

I have tried to find out where the wrong is. can anyone please help for this one . if I try to submit the post without an image, this error comes up instead of a flash message:

and source code link: https://github.com/rizvi770/cart.git

TypeError: Cannot read property 'image' of null
    at /Users/rizvi/Desktop/cart/routes/admin_products.js:115:37
    at Layer.handle [as handle_request] (/Users/rizvi/Desktop/cart/node_modules/express/lib/router/layer.js:95:5)
    at next (/Users/rizvi/Desktop/cart/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/Users/rizvi/Desktop/cart/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/Users/rizvi/Desktop/cart/node_modules/express/lib/router/layer.js:95:5)

and While submit the post with every details of the schema, then these error comes up:

events.js:298
      throw er; // Unhandled 'error' event
      ^

TypeError: invalid options argument
    at optsArg (/Users/rizvi/Desktop/cart/node_modules/mkdirp/lib/opts-arg.js:13:11)
    at mkdirp (/Users/rizvi/Desktop/cart/node_modules/mkdirp/index.js:11:10)
    at /Users/rizvi/Desktop/cart/routes/admin_products.js:175:19
    at /Users/rizvi/Desktop/cart/node_modules/mongoose/lib/model.js:4827:16
    at /Users/rizvi/Desktop/cart/node_modules/mongoose/lib/helpers/promiseOrCallback.js:24:16
    at /Users/rizvi/Desktop/cart/node_modules/mongoose/lib/model.js:4850:21
    at model.<anonymous> (/Users/rizvi/Desktop/cart/node_modules/mongoose/lib/model.js:490:7)
    at /Users/rizvi/Desktop/cart/node_modules/kareem/index.js:315:21
    at next (/Users/rizvi/Desktop/cart/node_modules/kareem/index.js:209:27)
    at /Users/rizvi/Desktop/cart/node_modules/kareem/index.js:182:9
    at /Users/rizvi/Desktop/cart/node_modules/kareem/index.js:507:38
    at processTicksAndRejections (internal/process/task_queues.js:79:11)
Emitted 'error' event on Function instance at:
    at /Users/rizvi/Desktop/cart/node_modules/mongoose/lib/model.js:4829:13
    at /Users/rizvi/Desktop/cart/node_modules/mongoose/lib/helpers/promiseOrCallback.js:24:16
    [... lines matching original stack trace ...]

Here is my route to post the product to the database:


router.post('/add-product',function(req,res){

   var imageFile = typeof req.files.image !== "undefined" ? req.files.image.name: "";

    req.checkBody('title','title must have value').notEmpty();
    req.checkBody('desc','Description must have value').notEmpty();
    req.checkBody('price','Price must have value').isDecimal();
    req.checkBody('image','You must upload an image').isImage(imageFile); 


    var title = req.body.title;
    var slug = title.replace(/\s+/g,'-').toLowerCase();
    var desc = req.body.desc;
    var price = req.body.price;
    var category = req.body.category;


    var errors = req.validationErrors();
    if(errors){ 
        Category.find(function(err, categories){
            res.render('admin/add_product', {
                errors : errors,
                title : title,
                desc : desc,
                categories : categories,
                price: price
            });
          });

    } else{ 
        Product.findOne({slug : slug}, function(err,product){


            if (product){
               req.flash('danger', ' This Product title already exists, choose another!!' );
               Category.find(function(err, categories){
               res.render('admin/add_product', {
                    title : title,
                    desc : desc,
                    categories : categories,
                    price: price
                });
              });

            } else {
                var price2 = parseFloat(price).toFixed(2);

                var product = new Product({

                   title: title,
                   slug : slug,
                   desc : desc,
                   price: price2,
                   category : category,
                   image: imageFile

                });
                product.save(function(err){

                if (err) 
                return console.log(err);

                  mkdirp('public/product_images/'+product._id, function(err){

                    return console.log(err);
                  });
                  mkdirp('public/product_images/'+product._id, function(err){

                    return console.log(err);
                  });
                  mkdirp('public/product_images/'+product._id + '/gallery', function(err){

                    return console.log(err);
                  });
                  mkdirp('public/product_images/'+product._id + '/gallery/thumbs', function(err){

                    return console.log(err);
                  });
              if (imageFile != ""){

                var productImage = req.files.image;
                var path = 'public/product_image/' + product._id + '/' + imageFile;

                productImage.mv(path, function(err){

                    return console.log(err);
                });

              }

                 req.flash('succes', 'product added!!');
                 res.redirect('/admin/products');
                });
            }
        }); 
    }


}); 

And here is my validation middleware:


customValidators:  {

     isImage: function(value, filename){
       var extension = (path.extname(filename)).toLowerCase();

       switch(extension){
        case '.jpg':
            return '.jpg';
        case '.jpeg':
            return '.jpeg'; 
        case '.png':
            return '.png'; 
        case '.':
            return 'jpg'; 

        default:
            return false; 
       }
     } 

    }

and here is my Public folder setup of app.js

// View Engine Setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// Set Public folder
app.use(express.static(path.join(__dirname,'public')));
app.use(express.static(__dirname + "/public"));

This Post Has One Comment

  1. No Fault

    put this 2 lines instead :

    if(!req.files){ imageFile =””; }

    if(req.files){

    var imageFile = typeof(req.files.image) !== “undefined” ? req.files.image.name : “”;
    Also a super simple fix for the mkdirp is to just install the 0.5.1 version for now untill someone can figure out how to fix the problem better

Leave a Reply