Skip to content

Latest commit

 

History

History
205 lines (181 loc) · 6.32 KB

4.7 注册.md

File metadata and controls

205 lines (181 loc) · 6.32 KB

4.7.1 用户模型设计

我们只存储用户的名称、密码(加密后的),对应修改 common/models.js,添加如下代码:

common/models.js

定义schema:

module.exports = {
    user:{
        name: {type: String,required: true},
        password: {type: String, required: true}
    },
    commodity: {
        name: String,
        price: Number,
        imgSrc: String
    },
    cart: {
        uId: {type: String},
        cId: {type: String},
        cName: { type: String},
        cPrice: { type: String},
        cImaSrc: { type: String},
        cQuantity: { type: Number},
        cStatus: { type: Boolean,default: false} 
    }
}

common/dbHelper.js

生成相应的model,并导出:

var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    models = require('./models');

for (var m in models) {
    mongoose.model(m, new Schema(models[m]));
}
module.exports = {
    getModel: function (type) {
        return _getModel(type);
    }
};

var _getModel = function (type) {
    return mongoose.model(type);
};

小提示:关于 mongoose 的 schema 的用法,请查阅 Mongoose快速入门

4.7.2 注册页

首先,我们来完成注册。新建 views/register.html,添加如下代码:

views/register.html

<!DOCTYPE html>
<html>
<head>
    <title>
        用户注册
    </title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="/stylesheets/bootstrap.min.css" media="screen">
    <script src="/javascripts/jquery-2.1.1.min.js" type="text/javascript"></script>
    <script src="/javascripts/bootstrap.min.js" type="text/javascript"></script>
    <style type="text/css">
        .panel-body{
            padding: 30px 50px 0 50px;
        }
        .form-group{
            margin-bottom: 35px;
        }
        .panel-title{
            font-size: 24px;
            font-weight: bold;
        }
    </style>
    <script type="text/javascript">
        function register(){
            var name = $('#username').val(),
                password = $('#password').val(),
                confirmpwd = $('#confirmpwd').val();
            var data = {"uname":name,upwd:password,ucpwd:confirmpwd};
            $.ajax({
                url: '/register',
                type: 'POST',
                data: data,
                success:function(data,status){
                    if(status == 'success'){
                        location.href = "login";
                    }
                },
                error:function(data,err){
                    location.href = "register";
                }
            });
        }
    </script>
</head>
<body>
  <div class="container web-body" style="margin-top:100px;width: 980px;">
    <%- message %>
    <div class="row">
        <div class="col-lg-6 col-lg-offset-3">
            <div class="panel panel-default">
                <div class="panel-heading" style="height: 50px;">
                    <div class="panel-title" style="text-align: left">用户注册</div>
                </div>
                <div class="panel-body">
                    <form action="#" class="form-horizontal" role="form" method="post" >
                        <div class="form-group">
                            <input id="username" type="text" class="form-control" name="username" placeholder="用户名" />
                        </div>
                        <div class="form-group">
                            <input id="password" type="password" class="form-control" name="password"  placeholder="密码" />
                        </div>
                        <div class="form-group">
                            <input id="confirmpwd" type="password" class="form-control" name="confirmpwd" placeholder="确认密码" />
                        </div>
                        <div class="form-group">
                            <input type="button" class="btn btn-success btn-block" onclick="register()" value="注 册" />
                            <a href="login" class="btn btn-primary" style="float: right;margin-top: 20px;">登 陆</a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>

注意:form 表单的提交时通过register()封装ajax请求。

修改 routes/register.js 中获取注册页的路由如下:

routes/signup.js

var sha1 = require('sha1');
module.exports = function (app) {
    app.get('/register', function (req, res) {
        res.render("register");
    });
    //解析表单,并写入数据库
    app.post("/register", function (req, res) {
        var User = global.dbHelper.getModel('user');
        var uname = req.body.uname;
        // 校验参数
        try {
            if (!(uname.length >= 1 && uname.length <= 10)) {
                throw new Error('名字请限制在 1-10 个字符');
            }
            if (req.body.ucpwd !== req.body.upwd) {
                throw new Error('两次输入密码不一致');
            }
        } catch (e) {
            // 注册失败
            req.session.error = e.message;
            return res.redirect('/register');
        }
        User.findOne({ name: uname }, function (error, doc) {
            if (error) {
                res.send(500);
                req.session.error = '网络异常错误!';
                console.log(error);
            } else if (doc) {
                req.session.error = "用户已存在!";
                res.send(500);
            } else {
                User.create({
                    name: uname,
                    password: sha1(req.body.upwd)
                }, function (error, doc) {
                    if (error) {
                        res.send(500);
                        console.log(error);
                    } else {
                        req.session.error = "用户创建成功!";
                        res.send(200);
                    }
                });
            }
        });
    });
}

现在访问 localhost:3000/register 看看效果吧。

上一节:4.6 连接数据库

下一节:4.8 登出与登录