Node.js form validation gives Cannot read property 'profileimage' of undefined - javascript

I am trying to make a form in Node.js using Express by following a tutorial. I am writing the validation logic which should show error messages if the form
gets submitted empty, however instead of doing that it gives me this error on line 33 and I can't figure out why:
Cannot read property 'profileimage' of undefined
I debugged it but couldn't figure out what is causing this.
What am I doing wrong, how can I fix it?
Here is the form code:
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('/register', function(req, res, next) {
res.render('register', {
'title': 'Register'
});
});
router.get('/login', function(req, res, next) {
res.render('login', {
'title': 'Log In'
});
});
router.post('/register', function(req, res, next) {
var name = req.body.name;
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
var password2 = req.body.password2;
// Check for Image Field
if(req.files.profileimage){
console.log('uploading File...');
// File Info
var profileImageOriginalName = req.files.profileimage.originalname;
var profileImageName = req.files.profileimage.name;
var profileImageMime = req.files.profileimage.mimetype;
var profileImagePath = req.files.profileimage.path;
var profileImageExt = req.files.profileimage.extension;
var profileImageSize = req.files.profileimage.size;
} else {
// Set a Default Image
var profileImageName = 'noimage.png';
}
// Form Validation
req.checkBody('name','Name field is required').notEmpty();
req.checkBody('email','Email field is required').notEmpty();
req.checkBody('email','Email not valid').isEmail();
req.checkBody('username','Username field is required').notEmpty();
req.checkBody('password','Password field is required').notEmpty();
req.checkBody('password2','Password do not match').equals(req.body.password);
// Check for errors
var errors = req.validationErrors();
if(errors){
res.render('register', {
errors: errors,
name: name,
email: email,
username: username,
password: password,
password2: password2
});
} else {
var newUser = new User({
name: name,
email: email,
username: username,
password: password,
profileImage: profileImageName
});
// Create User
User.createUser(newUser, function(err, user){
if(err)throw err;
console.log(user);
});
//Success Message
req.flash('success', 'You are now registered and may log in');
res.location('/');
res.redirect('/');
}
});
module.exports = router;
and my app.js:
var express = require('express');
var path = require('path');
var logger = require('morgan');
var expressValidator = require('express-validator');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var bodyParser = require('body-parser');
var multer = require('multer');
var flash = require('connect-flash');
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
var multer = require('multer');
var upload = multer({ dest: './uploads' });
// 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());
// Validator
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')));
app.use(flash());
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
app.get('*', function(req, res, next){
res.locals.user = req.user || null;
next();
});
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;

First of all files should be an array. If you are sure you send only one file try with this code block:
// Check for Image Field
if(req.files && req.files[0] && req.files[0].profileimage){
console.log('uploading File...');
// File Info
var profileImageOriginalName = req.files[0].profileimage.originalname;
var profileImageName = req.files[0].profileimage.name;
var profileImageMime = req.files[0].profileimage.mimetype;
var profileImagePath = req.files[0].profileimage.path;
var profileImageExt = req.files[0].profileimage.extension;
var profileImageSize = req.files[0].profileimage.size;
} else {
// Set a Default Image
var profileImageName = 'noimage.png';
}

You have the following line in your code:
if(req.files.profileimage){
when files is undefined, meaning, req does not have the property files (maybe a file was not sent on this request?), then trying to access anything within it will throw an error (and crash your node if you don't catch it)
So, first you should add type safety like so:
if(req.files && req.files.profileimage) {
or, even stricter, like so:
if(typeof req.files === 'object' && req.files.profileimage) {
(Note: you should do type safety test if and only if another part of your code has not already guaranteed that it is safe, e.g. a previous type safety test, or you assigned the property explicitly yourself in the code)
I also see that you are using multer to get a files object in your req object. Accroding to its docs, files can be an array, or an object of strings to arrays, From the "multer" npm page:
If used like so:
app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
It will be an array:
req.files is array of photos files
req.body will contain the text fields, if there were any
Or, if used like so:
var cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
app.post('/cool-profile', cpUpload, function (req, res, next) {
then it will be a (String -> Array) object:
req.files is an object (String -> Array) where fieldname is the key, and the value is array of files
e.g.
req.files['avatar'][0] -> File
req.files['gallery'] -> Array
So you should change your code accordingly. For example, if you choose the second method, you should change to the following:
if(typeof req.files === 'object' && req.files.profileimage) {
req.files.profileimage.forEach((profileimage) => {
//do anything you previously did on req.files.profileimage, on profileimage
let profileImageMime = profileimage.mimetype;
//... more things and code...
})
}

Related

Router.use() requires a middleware function but got undefined

I want make auth app using nodejs and got error like the title :(
but code for app.js is already like this
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var session = require('express-session')
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
secret: '123456cat',
resave: false,
saveUninitialized: true,
cookie: { maxAge: 60000 }
}))
app.use(express.static(path.join(__dirname, 'public')));
var registrationRouter = require('./routes/registration-route').default;
var loginRouter = require('./routes/login-route').default;
var dashboardRouter = require('./routes/dashboard-route').default;
var logoutRouter = require('./routes/logout-route');
app.use('/', registrationRouter);
app.use('/', loginRouter);
app.use('/', dashboardRouter);
app.use('/', logoutRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
app.listen(3000);
module.exports = app;
this is registration-route.js
var express = require('express');
var router = express.Router();
var db = require('../database');
// to display registration form
router.get('/register', function(req, res, next) {
res.render('registration-form');
});
// to store user input detail on post request
router.post('/register', function(req, res, next) {
inputData ={
username: req.body.username,
email_address: req.body.email_address,
password: req.body.password,
confirm_password: req.body.confirm_password
}
// check unique email address
var sql='SELECT * FROM registration WHERE email_address =?';
db.query(sql, [inputData.email_address] ,function (err, data, fields) {
if(err) throw err
if(data.length>1){
var msg = inputData.email_address+ "was already exist";
}else if(inputData.confirm_password != inputData.password){
var msg ="Password & Confirm Password is not Matched";
}else{
// save users data into database
var sql = 'INSERT INTO registration SET ?';
query(sql, inputData, function (err, data) {
if (err) throw err;
});
var msg ="Your are successfully registered";
}
res.render('registration-form',{alertMsg:msg});
})
});
module.exports = router;
login-route.js
var express = require('express');
var router = express.Router();
var db = require('../database');
/* GET users listing. */
router.get('/login', function(req, res, next) {
res.render('login-form');
});
router.post('/login', function(req, res){
var email = req.body.email;
var password = req.body.password;
var sql='SELECT * FROM registration WHERE email_address =? AND password =?';
db.query(sql, [email, password], function (err, data, fields) {
if(err) throw err
if(data.length>0){
req.session.loggedinUser= true;
req.session.email= email;
res.redirect('/dashboard');
}else{
res.render('login-form',{alertMsg:"Your Email Address or password is wrong"});
}
})
})
module.exports = router;
logout-route.js
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/logout', function(req, res) {
req.session.destroy();
res.redirect('/login');
});
module.exports = router;
dashboard-route.js
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/dashboard', function(req, res, next) {
if(req.session.loggedinUser){
res.render('dashboard',{email:req.session.emailAddress})
}else{
res.redirect('/login');
}
});
module.exports = router;
I already see questions like this but none of the answers are working for my case problem
also I'd tried to npm clear cache --force but nothing changed
also had been uninstalled and reinstalled for node_modules , package-lock but always got same error
Change all of these:
var registrationRouter = require('./routes/registration-route').default;
to remove the .default so you just have this:
const registrationRouter = require('./routes/registration-route');
.default is something that is used with ESM modules, not with CommonJS modules.
Also, you shouldn't be using var any more. It's obsolute now. Use const for these.

Where is the error in this Jade file?

Jade is not an easy language to deal with because of the proper indentation and what not, but in this case indentation does not seem to be the problem and I have Google-Foo'd the error and cannot find one that matches what is going on here.
This is my addpost.jade file:
extends layout
block content
h1=title
ul.errors
if errors
each error, i in errors
li.alert.alert-danger #{error.msg}
form(method='post', action='/posts/add', enctype="multipart/form-data")
.form-group
label Title:
input.form-control(name='title', type='text')
.form-group
label Category
select.form-control(name='category')
each category, i in categories
option(value='#{category.title}') #{category.title}
.form-group
label Body
textarea.form-control(name='body', id='body')
.form-group
label Main Image:
input.form-control(name='mainimage', type='file')
.form-group
label Author
select.form-control(name='author')
option(value='Daniel Cortes') Daniel Cortes
option(value='Alejandra Rocha') Alejandra Rocha
input.btn.btn-default(name='submit', type='submit', value='Save')
And this is the error I am getting:
addpost.jade:16 14| label Category 15| select.form-control(name='category') > 16| each category, i in categories 17| option(value='#{category.title}') #{category.title} 18| .form-group 19| label Body Cannot read property 'length' of undefined
This is my posts.js file:
var express = require('express');
var router = express.Router();
var mongo = require('mongodb');
var db = require('monk')('localhost/nodeblog');
router.get('/add', function(req, res, next){
var categories = db.get('categories');
categories.find({},{},function(err, categories){
res.render('addpost',{
"title": "Add Post",
"categories": categories
});
});
});
router.post('/add', function(req, res, next){
// Get Form Values
var title = req.body.title;
var category = req.body.category;
var body = req.body.body;
var author = req.body.author;
var date = new Date();
if(req.files.mainimage){
var mainImageOriginalName = req.files.mainimage.originalname;
var mainImageName = req.files.mainimage.name;
var mainImageMime = req.files.mainimage.mimetype;
var mainImagePath = req.files.mainimage.path;
var mainImageExt = req.files.mainimage.extension;
var mainImageSize = req.files.mainimage.size;
} else {
var mainImageName = 'noimage.png';
}
// Form Validation
req.checkBody('title','Title field is required').notEmpty();
req.checkBody('body', 'Body field is required');
// Check errors
var errors = req.validationErrors();
if(errors){
res.render('addpost',{
"errors": errors,
"title": title,
"body": body
});
} else {
var posts = db.get('posts');
// Submit to db
posts.insert({
"title": title,
"body": body,
"category": category,
"date": date,
"author": author,
"mainimage": mainimage
}, function(err, post){
if(err){
res.send('There was an issue submitting the post');
} else {
req.flash('success','Post Submitted');
res.location('/');
res.redirect('/');
}
});
}
});
module.exports = router;
my app.js file:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var expressValidator = require('express-validator');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var bodyParser = require('body-parser');
var mongo = require('mongodb');
var db = require('monk')('localhost/nodeblog');
var multer = require('multer');
var flash = require('connect-flash');
var routes = require('./routes/index');
var posts = require('./routes/posts');
var app = express();
app.locals.moment = require('moment');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// Handle File Uploads & Multipart Data
// app.use(multer({dest: './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 }));
app.use(cookieParser());
// Express Session
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
// Express Validator
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(express.static(path.join(__dirname, 'public')));
// Connect Flash
app.use(flash());
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
// Make our db accessible to our router
app.use(function(req, res, next){
req.db = db;
next();
});
app.use('/', routes);
app.use('/posts', posts);
// 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;
It seems that the categories is not passed to the view or its not a array.
Can you add the code that render the template? May be we can find the problem there.

express-validator always invalid

Im building a project on the latest version of nodejs and express I have a basic site setup im just trying to make the user authentication work(learning from this)
but no matter what I do I cannot get the express-validator to validate it will just always be invalid
validator deprecated you tried to validate a undefined but this library (validator.js) validates strings only. Please update your code as this will be an error soon. node_modules/express-validator/lib/express_validator.js:338:41
This is the only error i get but im not sure what to do as everything seems to matchup with the github docs
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 session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var bodyParser = require('body-parser');
var expressValidator = require('express-validator');
var multer = require('multer');
var flash = require('connect-flash');
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
var multer = require('multer');
var upload = multer({ dest: './uploads' });
// uncomment after placing your favicon in /public
//app.use(favicon(__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());
// Validator
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')));
app.use(flash());
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
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;
routes/users.js
var express = require('express');
var router = express.Router();
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var User = require('../models/user');
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.get('/register', function(req, res, next) {
res.render('register',{
'title': 'Register'
});
});
router.get('/login', function(req, res, next) {
res.render('login',{
'title': 'Login'
});
});
router.post('/register',function(req, res, next){
// Get Form Values
var name = req.body.name;
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
var password2 = req.body.password2;
// Check for Image Field
if(req.files && req.files.profileImage){
console.log('Uploading File...');
// File Info
var profileImageOriginalName = req.files.profileimage.originalname;
var profileImageName = req.files.profileimage.name;
var profileImageMime = req.files.profileimage.mimetype;
var profileImagePath = req.files.profileimage.path;
var profileImageExt = req.files.profileimage.extension;
var profileImageSize = req.files.profileimage.size;
} else {
// Set a Default Image
var profileImageName = 'noimage.png';
}
// Form Validation
req.checkBody('name','Name field is required').notEmpty();
req.checkBody('email','Email field is required').notEmpty();
req.checkBody('email','Email not valid').isEmail();
req.checkBody('username','Username field is required').notEmpty();
req.checkBody('password','Password field is required').notEmpty();
req.checkBody('password2','Passwords do not match').equals(req.body.password);
// Check for errors
var errors = req.validationErrors();
if(errors){
res.render('register',{
errors: errors,
name: name,
email: email,
username: username,
password: password,
password2: password2
});
} else {
var newUser = new User({
name: name,
email: email,
username: username,
password: password,
profileimage: profileImageName
});
// Create User
User.createUser(newUser, function(err, user){
if (err) throw err;
console.log(user);
});
// Success Message
req.flash('success','You are now registered and may log in');
res.location('/');
res.redirect('/');
}
});
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.getUserById(id, function(err, user) {
done(err, user);
});
});
passport.use(new LocalStrategy(
function(username, password, done){
User.getUserByUsername(username, function(err, user){
if(err) throw err;
if(!user){
console.log('Unknown User');
return done(null, false,{message: 'Unknown User'});
}
User.comparePassword(password, user.password, function(err, isMatch){
if(err) throw err;
if(isMatch){
return done(null, user);
} else {
console.log('Invalid Password');
return done(null, false, {message:'Invalid Password'});
}
});
});
}
));
router.post('/login', passport.authenticate('local',{failureRedirect:'/users/login', failureFlash:'Invalid username or password'}), function(req, res){
console.log('Authentication Successful');
req.flash('success', 'You are logged in');
res.redirect('/');
});
module.exports = router;
views/register.jade
extends layout
block content
h1 Register
p Please register using the form below
ul.errors
if errors
each error, i in errors
li.alert.alert-danger #{error.msg}
form(method='post',action='/users/register',enctype='multipart/form-data')
.form-group
label Name
input.form-control(name='name', type='text',placeholder='Enter Name')
.form-group
label Email
input.form-control(name='email', type='email',placeholder='Enter Email')
.form-group
label Username
input.form-control(name='username', type='text',placeholder='Username')
.form-group
label Password
input.form-control(name='password', type='password',placeholder='Enter Password')
.form-group
label Confirm Password
input.form-control(name='password2', type='password',placeholder='Confirm Password')
.form-group
label Profile Image
input.form-control(name='profileimage', type='file')
input.btn.btn-default(name='submit', type='submit',value='Register')
Instead of .notEmpty() check with isEmpty()
Source : ValidateJS
isEmpty : validate.isEmpty(value)
Check if the given value is non empty. The following value are considered empty:
null
undefined
Empty strings
Whitespace only strings
Empty arrays
Empty objects

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:
https://github.com/danialfarid/ng-file-upload/issues/185
nodejs and express error when uploading file, "cannot read property of undefined"
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';
}
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
}

Nodejs with Express... post data not received in users.js from jade form

Windows 8.1
Nodejs with Express
Console output is...
$ npm start
> nodeauth#1.0.0 start e:\nodejs\_projects\nodeauth
> node ./bin/www
GET /users/register 200 525.115 ms - 2078
GET /stylesheets/style.css 304 7.118 ms - -
GET /stylesheets/bootstrap.css 304 7.198 ms - -
GET /javascripts/bootstrap.js 304 8.063 ms - -
Name is... undefined
reqName... undefined
PW is... undefined
PW2 is.. undefined
POST /users/register 200 79.328 ms - 2340
GET /stylesheets/bootstrap.css 304 7.847 ms - -
GET /stylesheets/style.css 304 7.378 ms - -
GET /javascripts/bootstrap.js 304 8.676 ms - -
register.jade is...
The form loads OK and appears to be correct
extends layout
block content
h1 Register
p Complete form for site registration
ul.errors
if errors
each error, i in errors
li.alert.alert-danger #{error.msg}
form(method='post',action='/users/register',enctype='multipart/form-data')
.form-group
input.form-control(name='name', type='text', placeholder='Full Name')
.form-group
input.form-control(name='email', type='email', placeholder='Valid Email')
.form-group
input.form-control(name='username', type='text', placeholder='Username')
.form-group
input.form-control(name='password', type='password', placeholder='Password')
.form-group
input.form-control(name='password2', type='password', placeholder='Confirm Password')
.form-group
label Profile Image
input.form-control(name='profileimage', type='file')
input.btn.btn-default(name='submit', type='submit', value='Register')
user.js is...
Values in the console.log statements are undefined in the console output.
The post method must not be sending anything from the form.
The values from the users.js errors array are displayed after submission.
Possible syntax error, but I'm not seeing it.
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('/register', function(req, res, next) {
res.render('register', {
'title': 'Register'
});
});
router.get('/login', function(req, res, next) {
res.render('login', {
'title': 'LogIn'
});
});
router.post('/register', function(req, res, next) {
// Get form values
var name = req.body.name;
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
var password2 = req.body.password2;
console.log('Name is... ', name);
console.log('reqName... ', req.body.name);
console.log('PW is... ', password);
console.log('PW2 is.. ', password2);
// Check for image field
if (req.body.profileimage) {
console.log('Uploading file...');
// File info
var profileImageOriginalName = req.files.profileimage.originalname;
var profileImageName = req.files.profileimage.name;
var profileImageMime = req.files.profileimage.mimetype;
var profileImagePath = req.files.profileimage.path;
var profileImageExt = req.files.profileimage.extension;
var profileImageSize = req.files.profileimage.size;
} else {
var profileImageName = 'noimage.png'; // default image
}
// Form validation using Express validator
req.checkBody('name', 'Name is required').notEmpty();
req.checkBody('email', 'Valid Email is required').notEmpty();
req.checkBody('email', 'Email is not valid').isEmail();
req.checkBody('username', 'Username is required').notEmpty();
req.checkBody('password', 'Password is required').notEmpty();
req.checkBody('password2', 'Passwords do not match').equals(req.body.password);
// Check for errors
var errors = req.validationErrors();
if (errors) {
res.render('register', { // Pass values back in so user does not have to retype
errors: errors,
name: name,
email: email,
username: username,
password: password,
password2: password2
});
} else {
// Create user object
var newUser = new User({
name: name,
email: email,
username: username,
password: password,
profileimage: profileImageName
});
// Create user
User.createUser(newUser, function(err, user){
if (err) throw err;
console.log(user);
});
// Success
req.flash('success', 'You are registered and may now login');
res.location('/');
res.redirect('/');
}
});
module.exports = router;
Also files does not seem to be valid in the following context...
if (req.files.profileimage) console.log('Uploading file...');
Changed to...
if (req.body.profileimage) console.log('Uploading file...');
but have not been able to test yet.
as for Middleware...
The Package.json is...
{
"name": "nodeauth",
"version": "1.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"body-parser": "~1.13.2",
"connect-flash": "*",
"cookie-parser": "~1.3.5",
"debug": "~2.2.0",
"express": "~4.13.1",
"express-messages": "*",
"express-session": "*",
"express-validator": "*",
"jade": "~1.11.0",
"mongodb": "*",
"mongoose": "*",
"morgan": "~1.6.1",
"multer": "^1.0.3",
"passport": "*",
"passport-http": "*",
"passport-local": "*",
"serve-favicon": "~2.3.0"
}
}
And the app.js file is...
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var expressValidator = require('express-validator');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var bodyParser = require('body-parser');
var multer = require('multer');
var flash = require('connect-flash');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;
var upload = multer({ dest: './uploads' });
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
var upload = multer({ dest: './uploads' });
// ??? app.use(multer({dest: './uploads'}));
// 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 ... Note: Passport middleware must be after Express session middleware above
app.use(passport.initialize());
app.use(passport.session());
// Validator
// In this example, the formParam value is going to get morphed into form body format useful for printing.
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 and Express-Messages
app.use(flash());
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
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;
npm install with Multer did not like...
app.use(multer({dest: './uploads'}));
So I changed it to...
var upload = multer({ dest: './uploads' });
Not really sure what proplems that will cause yet
I face exactly the same problem like this before. As a way around the problem, I add connect-multiparty module to my project using npm command :
npm install connect-multiparty --save
then I add the code bellow on top of my route file (user.js) just after the express variable definition.
var express = require('express');
..
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
and finally I use multipartMiddleware in my router that accept files upload.
...
router.post('/register', multipartMiddleware, function(req, res, next){
...
...
}
Be aware that this module is not recommend to use in all routes, use it only to the ones in which you want to accept uploads. Check the documentation for more detail https://www.npmjs.com/package/connect-multiparty
for use multer you need insert it like middleware:
var multer = require('multer');
var upload = multer({dest: 'uploads/'});
var fileLoad = upload.single('profileImage');
router.route('/register')
.post(fileLoad, function (req, res) {
.......
}

Categories

Resources