我是passport.js的新手。 我一直在关注以下博客注册用户
https://scotch.io/tutorials/easy-node-authentication-setup-and-local
但每次我运行服务器并且我加载/register
页面时都显示上述错误
TypeError:passport.authenticate不是函数 在module.exports(/home/punit/Documents/****/routes/index.js:10:34) 在Layer.handle [as handle_request](/home/punit/Documents/****/node_modules/express/lib/router/layer.js:95:5) 在trim_prefix(/home/punit/Documents/****/node_modules/express/lib/router/index.js:312:13) at /home/punit/Documents/****/node_modules/express/lib/router/index.js:280:7 在Function.process_params(/home/punit/Documents/****/node_modules/express/lib/router/index.js:330:12) 在下一个(/home/punit/Documents/****/node_modules/express/lib/router/index.js:271:10) at /home/punit/Documents/****/node_modules/connect-flash/lib/flash.js:21:5 在Layer.handle [as handle_request](/ home / punit / Documents / **** / node_modules / express / lib / router / layer.js:95:5)
我已检查变量是否填充在/routes/index.js文件中。
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var session = require('express-session');
var routes = require('./routes/index');
var users = require('./routes/users');
mongoose.connect("localhost:27017/****");
require('./models/strategies')(passport)
var app = express();
会话初始化如下
app.use(session({
secret: '*******',
resave: true,
saveUninitialized: false
})); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
app.use('/', routes);
app.use('/users', users);
app.use('/register', routes);
require('./routes/index')(app, passport)
strategies.js文件如下
var LocalStrategy = require('passport-local').Strategy
var Profile = require('./profile.js')
var ex = function (passport) {
passport.serializeUser(function (user, done) {
done(null, user.id)
});
passport.deserializeUser(function (id, done) {
Profile.findById(_id, function (err, user) {
done(err, user)
});
});
passport.use('register', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
},
function(req, mobile, password, done) {
process.nextTick(function() {
return done(null, false);
});
}))
}
console.log(ex)
module.exports = ex;
和routes / index.js文件如下
module.exports = function (app, passport) {
/* GET home page. */
app.get('/login', function(req, res, next) {
res.render('index', { title: 'Express' });
});
app.get('/register', function(req, res, next) {
res.render('register', { title: 'Express' });
});
app.post('/register', passport.authenticate('register', {
successRedirect: '/profile',
faliureRedirect: '/register',
faliureFlash: true // allows flash message
}), function(req, res, err) {
console.log(req)
})
}
任何形式的帮助都将受到赞赏。
答案 0 :(得分:1)
您应该在路线文件中使用路由器或传递app
只有一个可以使用。
//app.use('/', routes);
//app.use('/users', users);
//app.use('/register', routes);
require('./routes/index')(app, passport)
这样护照对象将在路线文件中可用。