可以注册,并提示无效的用户名/密码,但在用户成功登录时会因序列化用户错误而中断。我似乎无法弄清楚我做错了什么。我试图找出如何实现multer和上传个人资料图片,它打破了x(
路由/ user.js的
var express = require('express');
var router = express.Router();
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var User = require('../models/user');
// Register
router.get('/register', function(req, res){
res.render('register');
});
// Login
router.get('/login', function(req, res){
res.render('login');
});
// Register User
router.post('/register', function(req, res){
var firstName = req.body.firstName;
var middleName = req.body.middleName;
var lastName = req.body.lastName;
var email = req.body.email;
var phoneNumber = req.body.phoneNumber;
var password = req.body.password;
var password2 = req.body.password2;
// Validation
req.checkBody('firstName', 'First name is required').notEmpty();
req.checkBody('lastName', 'Last name is required').notEmpty();
req.checkBody('email', 'Email is required').notEmpty();
req.checkBody('email', 'Email is not valid').isEmail();
req.checkBody('password', 'Password is required').notEmpty();
req.checkBody('password2', 'Passwords do not match').equals(req.body.password);
var errors = req.validationErrors();
if(errors){
res.render('register',{
errors:errors
});
} else {
var newUser = new User({
firstName: firstName,
middleName: middleName,
lastName: lastName,
email:email,
phoneNumber: phoneNumber,
password: password
});
User.createUser(newUser, function(err, user){
if(err) throw err;
console.log(user);
});
req.flash('success_msg', 'You are registered and can now login');
res.redirect('/users/login');
}
});
passport.use(new LocalStrategy(
function(email, password, done) {
User.getUserByEmail(email, function(err, user){
if(err) throw err;
if(!user){
return done(null, false, {message: 'Unknown User'});
}
User.comparePassword(password, user.password, function(err, isMatch){
if(err) throw err;
if(isMatch){
return done(null, user);
} else {
return done(null, false, {message: 'Invalid password'});
}
});
});
}));
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.getUserById(id, function(err, user) {
done(err, user);
});
});
router.post('/login',
passport.authenticate('local', {successRedirect:'/', failureRedirect:'/users/login',failureFlash: true}),
function(req, res) {
res.redirect('/');
});
router.get('/logout', function(req, res){
req.logout();
req.flash('success_msg', 'You are logged out');
res.redirect('/users/login');
});
module.exports = router;
模型/ user.js的
var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');
// User Schema
var UserSchema = mongoose.Schema({
id:{
type: String,
index:true
},
email: {
type: String,
index:true
},
password: {
type: String
},
firstName: {
type: String
},
middleName: {
type: String
},
lastName: {
type: String
},
phoneNumber: {
type: String,
index:true
}
});
var User = module.exports = mongoose.model('User', UserSchema);
module.exports.createUser = function(newUser, callback){
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(newUser.password, salt, function(err, hash) {
newUser.password = hash;
newUser.save(callback);
});
});
}
app.js
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var exphbs = require('express-handlebars');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongo = require('mongodb');
var mongoose = require('mongoose');
var cloudinary = require('cloudinary');
mongoose.connect('mongodb://localhost/loginapp');
var db = mongoose.connection;
var routes = require('./routes/index');
var users = require('./routes/users');
// Init App
var app = express();
// View Engine
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', exphbs({defaultLayout:'layout'}));
app.set('view engine', 'handlebars');
// BodyParser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// Set Static Folder
app.use(express.static(path.join(__dirname, 'public')));
// Express Session
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
// Passport init
app.use(passport.initialize());
app.use(passport.session());
// Express Validator
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
// Connect Flash
app.use(flash());
// Cloudinary
cloudinary.config({
cloud_name: 'xxxxxxx',
api_key: 'xxxxxxxxx',
api_secret: 'xxxxxxxxx'
});
// Global Vars
app.use(function (req, res, next) {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
res.locals.user = req.user || null;
next();
});
app.use('/', routes);
app.use('/users', users);
// Set Port
app.set('port', (process.env.PORT || 3000));
app.listen(app.get('port'), function(){
console.log('Server started on port '+app.get('port'));
});
错误讯息:
错误:无法将用户序列化为会话 传递(C:\ Users \ Mike \ documents \ development \ web \ app \ node_modules \ pass 端口\ lib中\ authenticator.js:271:19) 在序列化(C:\ Users \ Mike \ documents \ development \ web \ app \ node_module 小号\护照\ lib中\ authenticator.js:276:7) 在C:\ Users \ Mike \ documents \ development \ web \ app \ routes \ users.js:84:3 传递(C:\ Users \ Mike \ documents \ development \ web \ app \ node_modules \ pass 端口\ lib中\ authenticator.js:284:9) 在Authenticator.serializeUser(C:\ Users \ Mike \ documents \ development \ web \ app \ node_modules \护照\ lib中\ authenticator.js:289:5) 在IncomingMessage.req.login.req.logIn(C:\ Users \ Mike \ documents \ development \ 网络\程序\ node_modules \护照\ LIB \ HTTP \ request.js:50:29) 在Strategy.strategy.success(C:\ Users \ Mike \ documents \ development \ web \ app \ node_modules \护照\ LIB \中间件\ authenticate.js:235:13) 已验证(C:\ Users \ Mike \ documents \ development \ web \ app \ node_modules \ 护照本地\ lib中\ strategy.js:83:10) 在C:\ Users \ Mike \ documents \ development \ web \ app \ routes \ users.js:75:14 在C:\ Users \ Mike \ documents \ development \ web \ app \ models \ user.js:55:6 在C:\ Users \ Mike \ documents \ development \ web \ app \ node_modules \ bcryptjs \ d IST \ bcrypt.js:261:17 在C:\ Users \ Mike \ documents \ development \ web \ app \ node_modules \ bcryptjs \ d IST \ bcrypt.js:1198:21 在Immediate.next(C:\ Users \ Mike \ documents \ development \ web \ app \ node_mo dules \ bcryptjs \ DIST \ bcrypt.js:1078:21) 在runCallback(timers.js:637:20) 在tryOnImmediate(timers.js:610:5) at processImmediate [as _immediateCallback](timers.js:582:5)错误:无法将用户序列化为会话 传递(C:\ Users \ Mike \ documents \ development \ web \ app \ node_modules \ pass 端口\ lib中\ authenticator.js:271:19) 在序列化(C:\ Users \ Mike \ documents \ development \ web \ app \ node_module 小号\护照\ lib中\ authenticator.js:276:7) 在C:\ Users \ Mike \ documents \ development \ web \ app \ routes \ users.js:84:3 传递(C:\ Users \ Mike \ documents \ development \ web \ app \ node_modules \ pass 端口\ lib中\ authenticator.js:284:9) 在Authenticator.serializeUser(C:\ Users \ Mike \ documents \ development \ web \ app \ node_modules \护照\ lib中\ authenticator.js:289:5) 在IncomingMessage.req.login.req.logIn(C:\ Users \ Mike \ documents \ development \ 网络\程序\ node_modules \护照\ LIB \ HTTP \ request.js:50:29) 在Strategy.strategy.success(C:\ Users \ Mike \ documents \ development \ web \ app \ node_modules \护照\ LIB \中间件\ authenticate.js:235:13) 已验证(C:\ Users \ Mike \ documents \ development \ web \ app \ node_modules \ 护照本地\ lib中\ strategy.js:83:10) 在C:\ Users \ Mike \ documents \ development \ web \ app \ routes \ users.js:75:14 在C:\ Users \ Mike \ documents \ development \ web \ app \ models \ user.js:55:6 在C:\ Users \ Mike \ documents \ development \ web \ app \ node_modules \ bcryptjs \ d IST \ bcrypt.js:261:17 在C:\ Users \ Mike \ documents \ development \ web \ app \ node_modules \ bcryptjs \ d IST \ bcrypt.js:1198:21 在Immediate.next(C:\ Users \ Mike \ documents \ development \ web \ app \ node_mo dules \ bcryptjs \ DIST \ bcrypt.js:1078:21) 在runCallback(timers.js:637:20) 在tryOnImmediate(timers.js:610:5) at processImmediate [as _immediateCallback](timers.js:582:5)