“TypeError: req.flash is not a function” 使用带有 nodejs、用户名和密码身份验证的通行证

bob*_*e01 2 javascript node.js passport.js

这是运行并输入错误密码时的控制台输出..

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)
Run Code Online (Sandbox Code Playgroud)

这是实际的代码。任何想法可能导致这种情况?..

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);
});
Run Code Online (Sandbox Code Playgroud)

Mat*_*ell 6

需要添加flash来express,这样才能作为中间件使用。

var flash = require('connect-flash');
...
app.use(flash());
Run Code Online (Sandbox Code Playgroud)

编辑:这样做的原因是 Flash 实际上并未内置到 Passport 或 Express 中,它是由connect-flash. 所以你需要用 npm 安装它,然后如上所示包含它。

  • 嗯,好吧……你有没有试过在你的本地策略中添加 `passReqToCallback` 选项?似乎它修复了这个人的错误:http://stackoverflow.com/questions/34310348/passport-and-connect-flash-req-flash-is-not-a-function (2认同)
  • 需要将 `flash` 中间件放在堆栈中更高的位置,在 `router` 之前,可能在护照之前。 (2认同)