app.js
var flash = require('connect-flash');
app.use(flash());
app.use(function(req, res, next) {
res.locals.errors = req.flash('error');
res.locals.infos = req.flash('info');
next();
});
reg.jade
extends layout
block contentinput(type="submit",value="注册")
reg.js
var router = require('express').Router();
var crypto = require('crypto'),
User = require('../models/user.js');
router
.get('/', function(req, res, next) {
res.render('reg', { title: '注册' });
})
.post('/', function(req, res) {
var name = req.body.name,
password = req.body.possword,
// pasword_re = req.body['password-repeat'];
password_re = req.body.password_re;
if (password_re != password) {
req.flash('error', '两次输入的值如一样');
return res.redirect('/reg'); //返回注册的首页
}
var md5 = crypto.createHash('md5'),
password = md5.update(req.body.password).digest('hex');
var newUser = new User({
name: req.body.name,
password: req.body.password,
email: req.body.email
});
User.get(newUser.name, function(err, user) {
if (user) {
req.flash('error', '用户已存在');
return res.redirect('/reg');
}
newUser.save(function(err, user) {
if (err) {
req.flash('error', err);
return res.redirect('/reg');
}
req.session.user = user;
req.flash('success', '注册成功');
res.redirect('/');
});
});
});
module.exports = router;