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 contentinclude left.jade
.row.right.col-lg-6
form.form-horizontal(method="post")
.err.col-lg-offset-2.text-center #{errors}
.form-group
label.col-lg-2.text-right(for="user1") 用户名:
.col-lg-10
input.user.form-control(type='text',placeholder="用户名",name="name",)
br
.form-group
label.col-lg-2.text-right(for="1") 密码:
.col-lg-10
input.password.form-control(type='password',placeholder="密码",name="password",)
br
.form-group
label.col-lg-2.text-right(for="1") 确认密码:
.col-lg-10
input.password.form-control(type='password',placeholder="确认密码",name="password_re",)
br
.form-group
label.col-lg-2.text-right(for="1") 邮箱:
.col-lg-10
input.email.form-control(type='email',placeholder="ace@ef.com",name="email",)
br
.col-lg-10.col-lg-offset-2
input(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;