I seem to be having a problem when applying a user to a session. When I login, the function runs perfect and bcrypt check the password perfectly. But when the req.session.user = user is called I get Cannot set property user of undefined.
Here is my users.js file
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');
var expressValidator = require('express-validator');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
router.use(expressValidator);
var UserModel = require('../models/user');
/* GET users listing. */
router.get('/register', function(req, res, next) {
res.send('respond with a resource');
});
router.get('/login', function(req, res, next) {
res.send('respond with a resource');
});
router.registerUser = function(req,res){
console.warn('Getting Here');
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(req.body.name);
var newUser = new UserModel({
name:name,
email:email,
username:username,
password: password
});
UserModel.createUser(newUser, function(err,user){
if(err) throw err;
console.log(user);
});
}
router.login = function(req,res){
var username = req.body.username;
var password = req.body.password;
UserModel.findById("584340be3f63a303484eccc0", function(err, user){
console.warn(user.username);
console.warn(user.password);
bcrypt.compare(password , user.password, function(err,res) {
if (err) throw err;
});
console.warn (user);
req.session.user = user;
console.warn(req.session.user);
})
}
module.exports = router;
As you can see in the file im finding a user in the DB and comparing its string. If the strings are correct I just want to add the user to the session. Here is my app.js file where the middleware is housed.
var session = require('express-session');
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 expressValidator = require('express-validator');
var flash = require('connect-flash');
var passport = require('passport');
var LocalStrategy = require('passport-local'),Strategy;
var mongo = require('mongoose');
var routes = require('./routes/index');
var users = require('./routes/users');
var candidates = require('./routes/candidates.js');
var supporters = require('./routes/supporters.js');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// 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());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.get('/candidates', candidates.findAll);
app.get('/candidates/:id', candidates.findOne);
app.put('/candidates/:id/votes', candidates.incrementUpvotes);
app.delete('/candidates/:id', candidates.deleteCandidate);
app.get('/supporters', supporters.findAll);
app.get('/supporters/:id', supporters.findOne);
app.post('/supporters',supporters.addPerson);
app.post('/candidates', candidates.addPerson);
app.post('/candidates/:id',candidates.updateCandidate);
app.post('/image',candidates.addImage);
app.post('/register', users.registerUser);
app.post('/login', users.login);
app.delete('/supporters/:id', supporters.deleteSupporter);
// catch 404 and forward to error handler
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(session({
cookieName: 'session',
secret: 'random_string_goes_here',
duration: 30 * 60 * 1000,
activeDuration: 5 * 60 * 1000,
}));
app.use(passport.initialize());
app.use(passport.session());
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
};
}
}
));
//Connect Flash
app.use(flash());
app.use(function(req,res,next){
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
next();
});
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;
I've been at this problem for quite a while now and was wondering if anyone can send me in the right direction. Thanks in advance!
I found the issue. In app.js I had some of my app.use functions placed below the app.user('router') and it was causing the issue
Related
Am a newbie to Node.js, Am getting only a loading page in node.js post request when running the passport authentication. Can anyone help me
my Router.js
var express = require('express');
var router = express.Router();
var passport = require('passport');
var User = require('../models/user-model');
var Local = require('../config/passport-local');
/* GET home page. */
router.get('/', function(req, res, next){
res.render('index',{ title : 'Login'});
});
router.post('/login', (req, res, next) => {
passport.authenticate('local',(req, res,next) => {
console.log('ok');
});
}, (req, res, next) => {
});
module.exports = router;
passport-local.js
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var User = require('../models/user-model')
passport.use(new LocalStrategy(
function(username, password, next) {
console.log('auth');
User.findOne({username: username}, function(err, user) {
console.log('passport');
if(err) { return next(err);}
if(!user) {
return next(null, false, {message : 'invalid username'});
}
if(!user.validPassword(password)) {
return next(null, false, {message: 'invalid password'})
}
return next(null, user);
});
}
));
App.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mongoose = require('mongoose');
var passport = require('passport');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var commonKeys = require('./config/keys');
var app = express();
//connect mongoDb
mongoose.connect(commonKeys.mongoDB.connect + '/' + commonKeys.mongoDB.database, { useNewUrlParser: true });
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use('/', indexRouter);
app.use('/users', usersRouter);
// 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');
});
module.exports = app;
I am trying to learn passport authentication in nodejs. it is much appriciated if anyone can explain the error in this code and why its not working.
You need to update your code accordingly:
router.post('/login',
passport.authenticate('local'),
function(req, res) {
// If this function gets called, authentication was successful.
// `req.user` contains the authenticated user.
res.send('Done');
});
Here's more documentation.
I'm using req.session.userID variable to set a sessionID for the user.
My code is
On the server side,
router.post('/signin', bodyParser.json(),function(req, res){
var db = req.db;
var collection = db.get('userCollection');
var name = req.body.name;
var password = req.body.password;
name = name.trim();
password = password.trim();
collection.find({"name":name}, {}, function(e1, username){
if (e1 === null){
if (username[0].password == password) {
req.session.userID = username[0]._id;
var string2 = "before session" + req.session.userID + "after session" + username[0]._id;
res.send(string2);
}
else {
res.send("Failure!");
}
}
});
And on the client side
router.post('/signin', bodyParser.json(),function(req, res){
var db = req.db;
var collection = db.get('userCollection');
var name = req.body.name;
var password = req.body.password;
name = name.trim();
password = password.trim();
collection.find({"name":name}, {}, function(e1, username){
if (e1 === null){
if (username[0].password == password) {
req.session.userID = username[0]._id;
var string2 = "before session" + req.session.userID + "after session" + username[0]._id;
res.send(string2);
}
else {
res.send("Failure!");
}
}
});
I have also set a secret token for in my app.js as advised in some other answers, but still whenever I user req.session.userID it gives me an error.
The moment I remove req.session.userID and just send a normal statement back it works. Can anyone tell me what could be the possible reason for this.
My app.js looks something like this...
var session = require('express-session');
app.use(session({
secret: 'secret token'
}))
I have even installed express-session. Should I be doing something else too?
Full app.js code,
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/learnproject1');
var logger = require('morgan');
var bodyParser = require('body-parser');
var indexRouter = require('./routes/myroutes.js');
//var userRouter = require('.')
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(function(req,res,next){
req.db = db;
next();
});
app.use('/', indexRouter);
//app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
app.use(session({
secret: 'secret token'
}))
// 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');
});
module.exports = app;
I've spent more time than I'd like to admit scouring countless posts online that have the same problem as me, to no avail. The majority of solutions seemed to be things like not including
passReqToCallback: true in my LocalStrategy.
passport.serializeUser() and passport.deserializeUser() in my init file.
app.use(passport.initialize()) and app.use(passport.session()) in app.js.
Requiring and using app.use(cookieParser()) in app.js.
Passing cookie parser my secret key.
Adding proxy and cookie attributes to my expressSession variable in app.js.
Invoking req.login inside passport.authenticate within my page route.
And several other little tweaks I can't remember...
My login.js is as follows;
var LocalStrategy = require('passport-local').Strategy;
var User = require('../../models/user');
var bCrypt = require('bcrypt-nodejs');
module.exports = function(passport) {
passport.use('login', new LocalStrategy({passReqToCallback: true},
function(req, username, password, done) {
//Queries MongoDB For User
User.findOne({'username': username}, function(err, user) {
//In The Event Of An Error, Throw It
if (err) {
return done(err);
}
//Username Does Not Exist, Log Error, Callback, Flash Error Message
if (!user){
console.log('User: '+ username + ", does not exist.");
return done(null, false, req.flash('message', 'User Not found.'));
}
//User Exists, But Password Is Incorrect
if (!isValidPassword(user, password)){
console.log('Invalid Password');
return done(null, false, req.flash('message', 'Invalid Password')); // redirect back to login page
}
//If No Previous Error Conditions Are Met - Username/Password Are Correct
console.log("Validated User: " + username + ".");
//req.user = user;
return done(null, user);
}); //End of User.findOne()
}) //End of new LocalStrategy
); //End of passport.use()
/*
var isValidPassword = function(user, password){
return bCrypt.compareSync(password, user.password);
}
*/
//Passwords are not currently hashed in my DB, so ignore bcrypt for now.
var isValidPassword = function(user, password) {
return user.password == password;
}
}
My passport-init.js file
var login = require('./login');
var User = require('../../models/user');
module.exports = function(passport){
//Serialise User
passport.serializeUser(function(user, done) {
console.log("Serializing User: " + user.username + "\n" + user + ".");
done(null, user._id);
});
//De-Serialise User
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
console.log("Deserializing User: " + user.username + "\n" + user);
done(err, user);
});
});
//Setting up Passport Strategy for Login
login(passport);
}
My index.js file contains the POST Login route
/* POST Login Page*/
router.post('/login', passport.authenticate('login', {
successRedirect: '/dashboard',
failureRedirect: '/login',
failureFlash: true
}));
And dashboard.js contains all the routing for /dashboard/other-pages.
These ones are protected by the isAuthenticated function.
var express = require('express');
var router = express.Router();
var database = require('../public/javascripts/db-connect.js');
var isAuthenticated = function(req, res, next) {
console.log("User: " + req.user);
console.log("Authenticated?: " + req.isAuthenticated());
if (req.isAuthenticated()) {
return next();
} else {
res.redirect('/unauthorised');
}
}
module.exports = function(passport) {
//Routes /dashboard --> dashboard.pug
router.get('/', isAuthenticated, function(req, res, next) {
database.getData("busdata", function(err, data) {
if (err) {
console.error(err);
} else {
res.render('dashboard', {title: 'Dashboard', busdata: data});
}
});
});
//Routes /dashboard/journeys --> journeys.pug
router.get('/journeys', isAuthenticated, function(req, res, next) {
database.getData("journeydata", function(err, data) {
if (err) {
console.error(err);
} else {
res.render('journeys', {title: 'Journey Graphs', journeydata: data});
}
});
});
return router;
}
So when I run the app;
I check localhost:3000/dashboard and localhost:3000/dashboard/journeys. They correctly re-direct me to /unauthorised.
Navigate to /login.
Enter a correct username and password, the console then spits out:
Validated User: TomPlum. Meaning passport.use() reached return done(null, user)
Serialising User: TomPlum + the objects properties
POST /login 302 time ms
User: undefined from isAuthenticated
isAuthenticated? false
GET /dashboard 302 time ms
Deserialising User: TomPlum + the objects properties
I'm then redirected to /unauthorised as isAuthenticated() evaluates to false.
Why is req.user undefined? Should I be using a LocalStrategy if my MongoDB is not-local? (Amazon Atlas Server). Other forum posts have suggested it could be a cookie issue but I've included the relevant cookie-parser includes in my app.js file.
app.js is here in-case it's an order issue.
//Require Variables
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');
//Mongo DB Connection Settings
var dbConfig = require('./db'); //db.js contains DB URL
var mongoose = require('mongoose');
mongoose.connect(dbConfig.url); //dbConfig.url refers to the export in db.js
//Page Routing
//var index = require('./routes');
var users = require('./routes/users');
var dashboard = require('./routes/dashboard')(passport);
var app = express();
app.d3 = require('d3');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public/images', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser('urban_sensing'));
app.use(express.static(path.join(__dirname, 'public')));
//app.use('/', index);
app.use('/dashboard', dashboard);
app.use('/users', users);
//Configuring Passport
var passport = require('passport');
var expressSession = require('express-session');
app.enable('trust-proxy');
app.use(expressSession({
secret: 'urban_sensing',
resave: true,
saveUninitialized: true,
proxy: true,
cookie: {
secure: true,
maxAge: 3600000
}
}));
app.use(passport.initialize());
app.use(passport.session());
//Flash Messaging For Passport
var flash = require('connect-flash');
app.use(flash());
//Initialize Passport
var initPassport = require('./public/javascripts/passport-init');
initPassport(passport);
var index = require('./routes/index')(passport);
app.use('/', index);
//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 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');
});
module.exports = app;
Some of the app.use(expressSession({..})); properties may currently be unnecessary as they've been added in an attempt to fix the issue.
Any help would be appreciated.
After too much time on this, turns out it was simply the order of app.js.
By moving
var dashboard = require('./routes/dashboard')(passport);
app.use('/dashboard', dashboard);
below all the passport configuration. It now works correctly. It seems that something wasn't initialised correctly during the routing of /dashboard when it was before the passport code.
Updated app.js
//Require Variables
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');
//Mongo DB Connection Settings
var dbConfig = require('./db'); //db.js contains DB URL
var mongoose = require('mongoose');
mongoose.connect(dbConfig.url); //dbConfig.url refers to the export in db.js
//Page Routing
//var index = require('./routes');
var users = require('./routes/users');
var app = express();
app.d3 = require('d3');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public/images', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser('urban_sensing'));
app.use(express.static(path.join(__dirname, 'public')));
//app.use('/', index);
app.use('/users', users);
//Configuring Passport
var passport = require('passport');
var expressSession = require('express-session');
app.use(expressSession({
secret: 'urban_sensing',
resave: false,
saveUninitialized: true,
cookie: {
maxAge: 3600000 //1 Hour
}
}));
app.use(passport.initialize());
app.use(passport.session());
//Flash Messaging For Passport
var flash = require('connect-flash');
app.use(flash());
//Initialize Passport
var initPassport = require('./public/javascripts/passport-init');
initPassport(passport);
var dashboard = require('./routes/dashboard')(passport);
app.use('/dashboard', dashboard);
var index = require('./routes/index')(passport);
app.use('/', index);
//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 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');
});
module.exports = app;
I m learning from fast record on youtube. calls "Learn NodeJS building 10 projects". he is doing that at 15. video. Well this is my first post here. dont yell me cuz its my first message here. and please use easy english :) salute from turkey.
///THIS IS THE APP.JS
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 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 multer
//app.use(multer({dest:'./uploads'}));
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-session
app.use(session({
secret:'secret',
saveUninitialized: true,
resave:true
}));
// passport
app.use(passport.initialize());
app.use(passport.session());
// 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(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// connect-flash
app.use(flash());
// express-messages
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;
------------------------------
THIS IS THE USERS.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('/yenihesap', function(req, res, next) {
res.render('yenihesap',{
'title': 'Yeni Hesap Aç'
});
});
router.get('/giris', function(req, res, next) {
res.render('giris',{
'title': 'Giriş Yap'
});
});
router.get('/sifremiunuttum', function(req, res, next) {
res.render('sifremiunuttum',{
'title': 'Şifremi Unuttum'
});
});
router.post('/yenihesap', function(req, res, next){
// get form values
var name = req.body.name;
var lastname = req.body.lastname;
var email = req.body.email;
var password = req.body.password;
var password2 = req.body.password2;
// form validation
req.checkBody('name', 'Lütfen isminizi giriniz').notEmpty();
req.checkBody('lastname', 'Lütfen soyadınızı giriniz').notEmpty();
req.checkBody('email', 'Lütfen email adresinizi giriniz').notEmpty();
req.checkBody('email', 'Bu bir email adresi değil!').isEmail();
req.checkBody('password', 'Lütfen şifrenizi giriniz').notEmpty();
req.checkBody('password2', 'Şifreniz eşleşmiyor!').equals(req.body.password);
// check for errors
var errors = req.validationErrors();
if(errors){
res.render('yenihesap',{
errors: errors,
name: name,
lastname: lastname,
email: email,
password: password,
password2: password2
});
}else{
var newUser = new User({
name: name,
lastname: lastname,
email: email,
password: password
});
// create user
//User.createUser(newUser, function(err, user){
// if(err) throw err;
// console.log(user);
//});
//succes message
req.flash('success', 'Başarıyla kayıt oldunuz');
res.location('/');
res.redirect('/');
}
});
module.exports = router;
this is the jade file
when even i full up to input forms correctly, all errors that i have. i dont understand why
I found the problem. Its about the multer. first of all it wasnt work with that code at the beggining
//handle file uploads multer
app.use(multer({dest:'./uploads'}));
the multer was giving me error and changed it to that
//handle file uploads multer
var upload = multer({ dest: './uploads' });
and this time multer had me this question problem that body parser wasnt work. so I changed to that. and it fixed my problem. I found it another question on stackover: typeerror: app.use() requires middleware function
//handle file uploads multer
app.use(multer({dest:'./uploads/'}).single('singleInputFileName'));
I m happy to joined this site. Its obviously perfect that people help each other. see you on next problems :)
Welcome to Git (version 1.9.5-preview20150319)
Run 'git help git' to display the help index.
Run 'git help ' to display help for specific commands.
$ npm start
nodeauth#1.0.0 start C:\Users*****\Desktop\nodeauth
node ./bin/www
C:\Users***\Desktop\nodeauth\node_modules\express\lib\application.js:206
throw new TypeError('app.use() requires middleware functions');
^
TypeError: app.use() requires middleware functions
at EventEmitter.use >>...>
//app.js
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 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'}));
// 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;
You need to use app.use(multer({dest:'./uploads/'})) in the form of one of these:
app.use(multer({dest:'./uploads/'}).single(...));
app.use(multer({dest:'./uploads/'}).array(...));
app.use(multer({dest:'./uploads/'}).fields(...));
ie:
app.use(multer({dest:'./uploads/'}).single('photo'));
And be sure to have something like:
<form action="/postPhotos" enctype="multipart/form-data">
<input type="file" name="photo">
<input type="submit" value="Upload photo">
</form>
In your html.