I'm learning flash
messaging in passport
and got stuck on this error when running my script:
req.flash is not a function
Here is my configuration:
var flash=require("connect-flash");
app.use(flash());
passport.use(new LocalStrategy(function(req,username, password,done) {
process.nextTick(function() {
UserDetails.findOne({'username': username}, function(err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false,req.flash('message','Invalid username or password'));
}
if (user.password != password) {
return done(null, false,req.flash('message','Invalid username or password' ));
}
return done(null, user);
});
});
}));
My route:
app.get('/', function (req, res) {
res.render('login',{ message: req.flash('message') });
});
My strategy:
app.post('/login', function(req,res,next){
passport.authenticate('local', function(err, user) {
if (err) { return next(err); }
if (!user) { return res.redirect('/')}
req.logIn(user, function(err) {
if (err) { return next(err); }
arenderFunction(req,res);
});
})
(req, res, next);
});
Any help is much appreciated!
Note: Using flash messages requires a req. Use of connect-flash middleware is recommended to provide this functionality when using Express 3. x. So you need to install connect-flash express middleware as it is recommended. var flash = require('connect-flash'); var app = express(); app.
Connect-flash module for Node. js allows the developers to send a message whenever a user is redirecting to a specified web-page. For example, whenever, a user successfully logged in to his/her account, a message is flashed(displayed) indicating his/her success in the authentication.
The express-flash module exposes getter and setter methods for a flash message of the form, { flash: { type: 'type', message: 'message' }} and depends on the express-session module. The method req. flash(type, message) sets the value of a new flash message and adds it to an array of messages of the same type.
The request object isn't passed to the strategy callback by default, you need to set the passReqToCallback
option for this:
passport.use(new LocalStrategy({
passReqToCallback : true
}, function(req, username, password, done) { ... }));
This is documented here.
Set flash before the app.router
app.use(express.cookieParser());
app.use(express.session({ secret: "secret" }));
//app.use(passport.initialize());
//app.use(passport.session()); // persistent login sessions
app.use(flash());
app.use(app.router);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With