Erik hoeven Erik hoeven - 6 months ago 105
Node.js Question

Cannot read property of undefined when uploading empty file

I'm using Node.js (v0.10.25) and Express (4.13.1) and using jade instead of HTML. I have a registration form where a user can registrate and upload a profileimage.

All works fine except when I upload an empty image then the I get the following error:

Cannot read property 'profileimage' of undefined

APP.JS

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var methodOverride = require('method-override');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var multer = require('multer');
var flash = require('connect-flash');
var expressValidator = require('express-validator');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;


var routes = require('./routes/index');
var users = require('./routes/users');



var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// Handle file Uploads
app.use(multer({dest:'./uploads/'}).single('singleInputFileName'));

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

//Handle Express Sessions
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));


//Passport
app.use(passport.initialize());
app.use(passport.session());

//Vallidator
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;

while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));



app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


// Flash
app.use(flash());

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});


module.exports = app;


USER.JS

var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});

router.get('/Registreren', function(req, res, next) {
res.render('Registration', { title: 'Registreren' });
});

router.get('/Aanmelden', function(req, res, next) {
res.render('Aanmelden', { title: 'Aanmelden' });
});

router.post('/Registreren', function(req, res, next){
// Get form value
console.log('Bericht in behandeling ...')
var username = req.body.username;
var email = req.body.email;
var password = req.body.password;
var password_confirm = req.body.password_confirm;

console.log('username: ' + username);
console.log('email: ' + email);
console.log('password: ' + password);
console.log('password_confirm: ' + password_confirm);
console.log('FIRST TEST: ' + JSON.stringify(req.files));
console.log('SECOND TEST: ' + req.files.profileimage);

// Check for image field
if (req.files.profileimage){
console.log('Uploading file....');

//File Info
var profileImageOrginalName = req.files.profileimage.orginalname;
var profileImageName = req.files.profileimage.name;
var profileImageMimetype = req.files.profileimage.mimetype;
var profileImagePath = req.files.profileimage.path;
var profileImageExt = req.files.profileimage.extension;
var profileImageSize = req.files.profileimage.size;
} else{
console.log('profileImageFile not found....');
// Set default image
var profileImageName = 'noimage.png';
}

// Form validation
req.checkbody('username','Gebruikersnaam is verplicht').notEmpty();
req.checkbody('email','email is verplicht').notEmpty();
req.checkbody('email','email is niet geldig').isEmail();
req.checkbody('username','Gebruikersnaam is verplicht').notEmpty();
req.checkbody('password','Gebruikersnaam is verplicht').notEmpty();
req.checkbody('password_confirm','Wachtwoorden zijn niet gelijk').equals(req.body.password);
req.checkbody('username','Gebruikersnaam is verplicht').notEmpty();

// Error handling
console.log('Error handling....');
var errors = req.valdidationErrors();

if (errors){
console.log('Form Errors....');
res.render('Registreren',{
errors: errors,
username: username,
email: email,
password: password,
password_confirm: password_confirm
});
}else {
console.log('No Form Errors....');
var newUser = new User({
username: username,
email: email,
password: password,
profileimage: profileImageName })

// Create User
// User.createUser(newUser, function(err,user){
// if(err) throw err;
// console.log(user);
// });

// Succes message
req.flash('succes','Je bent succesvol aangemedld');
res.location('/');
res.redirect('/');
}

});



module.exports = router;


What I have read and tried:


  1. https://github.com/danialfarid/ng-file-upload/issues/185

  2. nodejs and express error when uploading file, "cannot read property of undefined"

  3. TypeError: Cannot read property 'image' of undefined



On the USER.JS it give the result "undifned" on the first test and on the second test it fails completely. Also I get nog cosole.log for the else statement in the

if (req.files.profileimage){
console.log('Uploading file....');

//File Info
var profileImageOrginalName = req.files.profileimage.orginalname;
var profileImageName = req.files.profileimage.name;
var profileImageMimetype = req.files.profileimage.mimetype;
var profileImagePath = req.files.profileimage.path;
var profileImageExt = req.files.profileimage.extension;
var profileImageSize = req.files.profileimage.size;
} else{
console.log('profileImageFile not found....');
// Set default image
var profileImageName = 'noimage.png';
}

Answer

Make sure req.files exists or you will get undefined errors. i.e.:

if (req.files && req.files.profileImage) {
  // only if there are files
} else {
  // You should see this now
}