简体   繁体   中英

“TypeError: req.flash is not a function” using passport with nodejs, username and password auth

Heres console output when running and entering an incorrect password ..

info: Listening on 127.0.0.1:3000
debug: GET /
debug: Incorrect password
/home/bob/git/authenticate-nodejs-prototype/node_modules/mongodb/lib/utils.js:98
    process.nextTick(function() { throw err; });
                                  ^

TypeError: req.flash is not a function
    at allFailed (/home/bob/git/authenticate-nodejs-prototype/node_modules/passport/lib/middleware/authenticate.js:118:15)

Heres the actual code. Any ideas what might be causing this? ..

var express = require('express'),
    app = express(),
    http = require('http').Server(app),
    winston = require('winston'),
    passport = require('passport'),
    LocalStrategy = require('passport-local').Strategy,
    ipaddress = '127.0.0.1',
    port = 3000,
    MongoClient = require('mongodb').MongoClient,
    ObjectId = require('mongodb').ObjectID,
    assert = require('assert'),
    mongoUrl = 'mongodb://' + ipaddress + ':27017/authenticate-nodejs-prototype',
    flash = require('connect-flash');

// during dev
winston.level = 'debug';


/*
 * Database query
 * Searches db for user that matches provided username
 */
var findUser = function (db, id, callback) {
    var cursor = db.collection('userInfo').find({username: id.username});
    var result = [];
    cursor.each(function (err, doc) {
        assert.equal(err, null);
        if (doc !== null) {
            result.push(doc);
        } else {
            callback(result);
        }
    });
};


// configure passport to use username and password authentication
passport.use(new LocalStrategy(
  function(username, password, done) {
        MongoClient.connect(mongoUrl, function (err, db) {
            assert.equal(null, err);
            findUser(db, {username:username, password:password}, function (result) {
                db.close();

                if (err) {
                    return done(err);
                }else if (result === []) {
                    winston.debug('Incorrect username');
                return done(null, false, { message: 'Incorrect username.' });
              }else if (password !== result.password) {
                    winston.debug('Incorrect password');
                return done(null, false, { message: 'Incorrect password.' }); // this is the line that causes error
              }
              return done(null, result);
            });
        });
  }
));
passport.serializeUser(function(user, done) {
  return done(null, user);
});
passport.deserializeUser(function(id, done) {
    MongoClient.connect(mongoUrl, function (err, db) {
        assert.equal(null, err);
        findUser(db, id, function (result) {
            db.close();
            return done(null, result);
        });
    });
});

app.configure(function() {
  app.use(express.static('public'));
  app.use(express.cookieParser());
  app.use(express.bodyParser());
  app.use(express.session({ secret: 'keyboard cat' }));
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(app.router);
  app.use(flash());
});

/*
 * setup endpoints
  */
app.get('/', function(req, res){
    winston.debug('GET /');
  res.sendfile('views/index.html');
});
app.get('/success', function(req, res){
    winston.debug('GET /success');
  res.sendfile('views/success.html');
});
app.post('/login',
  passport.authenticate('local', { successRedirect: '/success',
                                   failureRedirect: '/',
                                   failureFlash: true })
);

// start server
http.listen(port, ipaddress, function(){
  winston.info('Listening on ' + ipaddress + ':' + port);
});

You need to add flash to express, so that it can be used as middleware.

var flash = require('connect-flash');
...
app.use(flash());

Edit: the reason for this is that flash isn't actually built into Passport or Express, it's a separate package provided by connect-flash . So you need to install it with npm and then include it as shown above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM