以下:
在app.js:
...
var session = require('express-session');
var passport = require('passport');
var flash = require('connect-flash');
var validator = require('express-validator');
...
var app = express();
require('./config/passport');
...
app.use(bodyParser.urlencoded({ extended: false }));
app.use(validator());
...
app.use(session({ secret: settings.session_key, resave: false, saveUninitialized: false }));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
在路由器/ index.js:
router.get('/register', function (req, res, next) {
var messages = req.flash('error');
res.render('customers/register', {
messages: messages,
hasErrors: messages.length > 0
}
}
router.post('/register', passport.authenticate('local.register', {
successRedirect: '/customer/dasdboard',
failureRedirect: '/customer/register',
failureFlash: true //required
}));
在查看/客戶/ signup.hbs:
{{#if hasErrors}}
<div class="alert alert-danger">
{{#each messages}}
<p>{{this}}</p>
{{/each}}
</div>
{{/if}}
在config/passport.js中:
passport.use('local.register', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true //required
}, function(req, email, password, done) {
req.checkBody('inputFirstName', 'First name empty').notEmpty();
req.checkBody('inputLastName', 'Last name empty').notEmpty();
req.checkBody('inputEmail', 'Invalid email').notEmpty().isEmail();
req.checkBody('password','Confirm password does not match.').equals(req.body.confirmpassword);
var errors = req.validationErrors();
if (errors) {
var messages = [];
errors.forEach(function(error){
messages.push(error.msg);
});
return done(null, false, req.flash('error', messages));
}
db.User.find({email: req.body.inputEmail}, function (err, user) {
if (err) {
return done(err);
}
if (user) {
return done(null, false, {message: 'Email address already registered!'});
}
//Save new data here
....
});
}));
爲我的解決方案工作。