未定义nodejs throw pass的护照(nodejs 0.12.7)

时间:2016-06-08 09:18:14

标签: node.js passport.js

我的应用使用passport用于auth用户,但它有时会抛出异常:

ReferenceError: pass is not defined at deserialized (node_modules/passport/lib/authenticator.js:345:7) at app/app.js:89:10

app.js是:

    var app, bodyParser, config, cookies, cors, e, express, http, keys, localStrategy, logger, multipart, passport, path, router, server, session, sessionStore, sessionUsed, session_store, util, uuid;

express = require('express');

http = require('http');

path = require('path');

session = require('express-session');

cors = require('cors');

session_store = require('sessionstore');

keys = require("keygrip")(['a', 'b']);

bodyParser = require('body-parser');

cookies = require('cookies').express;

passport = require('passport');

uuid = require('node-uuid');

multipart = require('connect-multiparty');

localStrategy = require('passport-local').Strategy;

config = require('./config/config');

util = require('./libs/util');

logger = require('./libs/logger');

sessionStore = session_store.createSessionStore(config.getMemCache());

sessionUsed = session({
  secret: config.getCookieSecret(),
  genid: function() {
    return uuid.v4();
  },
  cookie: {},
  saveUninitialized: true,
  resave: true,
  store: sessionStore
});

app = express();

router = express.Router();

app.set('port', process.env.PORT || config.getServerPort());

app.set('views', __dirname + '/../app/public');

app.set('view engine', 'html');

app.use(sessionUsed);

app.use(cors());

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({
  extended: true
}));

app.use(multipart({
  maxFilesSize: 2 * 1024 * 1024
}));

app.use(express["static"](path.join(__dirname, '/../app/public')));

app.use(cookies(keys));

app.use(passport.initialize());

app.use(passport.session());

passport.use('local', new localStrategy({
  passReqToCallback: true
}, util.checkUserPassword));

passport.serializeUser(function(user, done) {
  return done(null, user);
});

passport.deserializeUser(function(user, done) {
  return done(null, user);
});

require('./routes/router')(app, router, passport);

server = http.createServer(app);

try {
  server.listen(app.get('port'), function() {
    return logger.info('Express is running at:' + app.get('port'));
  });
} catch (_error) {
  e = _error;
  console.log(e);
}

我已经查看了抛出异常的代码,就像这样 enter image description here

1 个答案:

答案 0 :(得分:1)

首先,屏幕截图中未显示您的错误。在屏幕截图中,您将显示来自authenticator.js的line 282。您的错误消息会在line 345中显示问题的实际位置 - function deserialized

出现此错误的原因是您的app.js中的反序列化函数未传递用户对象。您的反序列化函数是序列化函数的副本,它不应该是。这两个应该是这样的:

passport.serializeUser(function(user, done){
    done(null, user.id);
});

passport.deserializeUser(function(id, done){
    User.findById(id, function(err, user){
        done(err, user);
    })
});

当然,您无法在不更改序列化功能的情况下使用此反序列化功能来存储user.id或某些唯一标识符,而不是尝试存储整个用户。我不知道当您尝试序列化整个用户时会发生什么,但我确信它会导致您的问题。

希望有所帮助!