node.js入门实现注册及登录

前端开发掌握的技能 前端开发必须掌握的技能 优秀前端开发技能

node.js的安装可以点击此链接进行学习配置;
我这里是用最简单的html页面去调用nodejs所写的api接口,适合初学者去理解,之后会慢慢改进,然后进行打包部署。
ps:可以推荐webStorm进行nodejs调试,可以定位到bug,并可以了解其的执行流程。
以下是我的目录结构:
html 代码

node-demo/
|
+- controllers/ <– Controller
| |
| +- login.js <– 登录注册处理
|
+- views/ <– html模板文件
| |
| +- login.html <– 登录页面
| |
| +- signUp.html <– 注册页面
|
+- public/ <– 静态资源文件
|
+- models <– models
| |
| +- db.js <– 数据库连接池设置
| |
| +- dao_mysql.js <– 数据库通用操作方法
| |
| +- query.js <– 数据库查询
|
+- router <– 路由文件
| |
| +- router.js <– 路由配置
|
+- app.js <– 入口文件
|
+- package.json <– 项目描述文件
|
+- node_modules/ <– npm安装的所有依赖包

1. 数据库操作:
链接池配置db.js
javascript 代码

/**
* Created by shana on 2017/6/15.
* 数据库连接池配置
*/
var mysql = require(‘mysql’) //npm install mysql
var pool = mysql.createPool({
    host: ‘localhost’,
    user: ‘root’,
    password: ”,
    database: ‘microblog’, //数据库名称
})
module.exports = pool

通用数据库增删查改操作dao_mysql.js
javascript 代码

/**
* Created by shana on 2017/6/15.
* 数据库操作
*/
var pool = require(‘./db.js’)
//通用数据库操作方法
module.exports.query = function(sql, param, callback) {
    //数据库连接
    pool.getConnection(function(err, connection) {
        if (err) {
            logger.error(err.message, err)
            if (callback) {
                callback(err)
            }
        } else {
            //连接成功则执行sql语句
            connection.query(sql, param, callback)
            //释放连接
            connection.release()
        }
    })
}

进行数据查询和插入的操作:
javascript 代码

/**
* Created by shana on 2017/6/15.
* 数据库操作
*/
var dao = require(‘./dao_mysql.js’)
module.exports = {
    /**
     * 根据用户名密码查询用户
     * @param
     */
    login: function(param, callback) {
        const name = param.name
        const password = param.password
        let sql =
            ‘select * from user where uname=”‘ +
            name +
            ‘” and upwd=”‘ +
            password +
            ‘”‘
        dao.query(sql, ”, function(err, result) {
            if (callback) {
                if (!err) {
                    let users = {
                        rows: result,
                    }
                    callback(null, users)
                } else {
                    callback(err)
                }
            }
        })
    },
    /**
     * 根据uid查询用户
     * @param uid
     */
    getUserById: function(uid, callback) {
        let sql = ‘select * from user’
        if (uid !== ” && uid !== undefined) {
            sql += ‘ where uid=’ + uid
        }
        let param = ”
        dao.query(sql, param, function(err, result) {
            if (callback) {
                if (!err) {
                    let users = {
                        rows: result,
                    }
                    callback(null, users)
                } else {
                    callback(err)
                }
            }
        })
    },
    /**
     * 添加用户
     * @param param
     */
    addUserInfo: function(param, callback) {
        let valFillArr = [],
            insertKey = [],
            insertValue = []
        for (let key in param) {
            valFillArr.push(‘?’)
            insertKey.push(‘user.’ + key)
            insertValue.push(param[key])
        }
        let sql =
            ‘insert user (‘ +
            insertKey.toString() +
            ‘) values (‘ +
            valFillArr.toString() +
            ‘)’
        dao.query(sql, insertValue, function(err, result) {
            if (err) {
                callback(err)
            } else {
                callback(null)
            }
        })
    },
    /**
     * 更新用户
     * @param param
     */
    updateUserInfo: function(param, callback) {
        let insertKey = [],
            insertValue = []
        for (let key in param) {
            if (param[key] != ” && key != ‘uid’) {
                insertKey.push(‘user.’ + key + ‘=?’)
                insertValue.push(param[key])
            }
        }
        let sql =
            ‘update user set ‘ + insertKey.toString() + ‘ where uid=’ + param.uid
        dao.query(sql, insertValue, function(err, result) {
            if (err) {
                callback(err)
            } else {
                callback(null)
            }
        })
    },
    /**
     * 删除用户
     * @param uid
     */
    deleteUserInfo: function(uid, callback) {
        let sql = ‘delete from user where uid=’ + uid
        let param = ”
        dao.query(sql, param, function(err, result) {
            if (err) {
                callback(err)
            } else {
                callback(null)
            }
        })
    },
}

2. controller中的login.js,与query.js进行交互
javascript 代码

/**
* Created by shana on 2017/6/15.
* 登录
*/
var query = require(‘../models/query.js’)
var log4js = require(‘log4js’) //日志
var log = log4js.getLogger(‘user’)
module.exports = {
    login: function(req, res) {
        let param = req.body //在app.js中要引入’body-parser’,用于处理 JSON, Raw, Text 和 URL 编码的数据
        let callback = function(err, result) {
            //返回结果到view中
            if (err) {
                log.error(‘login err: [ ‘ + err + ‘ ]’)
                res.json({
                    result: false,
                    errorMsg: ‘数据库连接失败’,
                    errorDetail: err.toString(),
                })
            } else {
                if (result.rows.length == 0) {
                    res.json({
                        result: false,
                        errorMsg: ‘登录失败’,
                    })
                } else {
                    req.session.user = result.rows // 将用户信息写入 session
                    res.json({
                        result: true,
                        errorMsg: ‘登录成功’,
                    })
                }
            }
        }
        query.login(param, callback)
    },
    register: function(req, res) {
        let param = req.body
        let callback = function(err, result) {
            if (err) {
                log.error(‘register err: [ ‘ + err + ‘ ]’)
                res.json({
                    result: false,
                    errorMsg: ‘数据库连接失败’,
                    errorDetail: err.toString(),
                })
            } else {
                res.json({
                    result: true,
                    errorMsg: ‘注册成功’,
                })
            }
        }
        query.addUserInfo(param, callback)
    },
}
// 对Date的扩展,将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,
// 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子:
// (new Date()).Format(“yyyy-MM-dd hh:mm:ss.S”) ==> 2006-07-02 08:09:04.423
// (new Date()).Format(“yyyy-M-d h:m:s.S”) ==> 2006-7-2 8:9:4.18
Date.prototype.Format = function(fmt) {
    //author: meizz
    var o = {
        ‘M+’: this.getMonth() + 1, //月份
        ‘d+’: this.getDate(), //日
        ‘h+’: this.getHours(), //小时
        ‘m+’: this.getMinutes(), //分
        ‘s+’: this.getSeconds(), //秒
        ‘q+’: Math.floor((this.getMonth() + 3) / 3), //季度
        S: this.getMilliseconds(), //毫秒
    }
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(
            RegExp.$1,
            (this.getFullYear() + ”).substr(4 – RegExp.$1.length),
        )
    for (var k in o)
        if (new RegExp(‘(‘ + k + ‘)’).test(fmt))
            fmt = fmt.replace(
                RegExp.$1,
                RegExp.$1.length == 1 ? o[k] : (’00’ + o[k]).substr((” + o[k]).length),
            )
    return fmt
}

3. 写app.js入口文件
javascript 代码

var express = require(‘express’)
var bodyParser = require(‘body-parser’) //用于处理 JSON, Raw, Text 和 URL 编码的数据
var app = express()
var router = require(‘./router/router’)
var session = require(‘express-session’) //用于登录拦截
//设置session配置
app.use(
    session({
        resave: false, //重新保存
        saveUninitialized: true, //
        secret: ‘ghost castle’, //通过设置的 secret 字符串,来计算 hash 值并放在 cookie 中,使产生的 signedCookie 防篡改。
        cookie: { maxAge: 1000 * 60 * 60 }, //失效时间
    }),
)
app.use(bodyParser.json()) //解析json数据
app.use(bodyParser.urlencoded({ extended: true })) //解析form表单提交上来的数据
app.use(express.static(‘public’)) //设置静态文件路径
app.use(‘/’, router) //路由跳转
var server = app.listen(3001, function() {
    var host = server.address().address
    var port = server.address().port
    console.log(‘http://%s:%s’, host, port)
})

4. 编写路由router.js
javascript 代码

/**
* Created by shana on 2017/8/15.
*/
var express = require(‘express’)
var router = express.Router()
var login = require(‘../controllers/login’)
//注册登录
router.post(‘/ghost/login’, login.login)
router.post(‘/ghost/register’, login.register)
// 总路由
router.use(function(req, res, next) {
    //登录拦截
    var url = req.originalUrl
    if (url != ‘/login’ && url != ‘/register’ && !req.session.user) {
        return res.redirect(‘/login’)
    }
    //next的作用是将请求转发,这个必须有,如果没有,请求到这就挂起了。
    next()
})
router.get(‘/login’, function(req, res) {
    res.sendfile(‘views/login.html’)
})
router.get(‘/register’, function(req, res) {
    res.sendfile(‘views/signUp.html’)
})
module.exports = router

到这里,node编写就完成了,接下来就是编写view中的html页面,并请求接口就可以啦~
页面中的css和js都放在静态目录public中,引入的bootstrap为最新版本。
login.html:
html 代码

<!DOCTYPE html>
<html lang=”en”>
<head>
    <meta charset=”UTF-8″>
    <meta name=”keywords” content=”your keywords”>
    <meta name=”description” content=”your description”>
    <meta name=”author” content=”author,email address”>
    <meta name=”robots” content=”index,follow”>
    <meta http-equiv=”X-UA-Compatible” content=”IE=Edge,chrome=1″>
    <meta name=”renderer” content=”ie-stand”>
    <title>Login</title>
    <link rel=”stylesheet” href=”/css/bootstrap.css”>
    <link rel=”stylesheet” href=”/css/font-awesome.css”>
    <link rel=”stylesheet” href=”/css/style.css”>
</head>
<body>
    <div class=”containers”>
        <nav class=”navbar navbar-expand-md navbar-dark bg-dark”>
            <a class=”navbar-brand” href=”#”>
                <i class=”fa fa-fort-awesome” aria-hidden=”true”></i> Ghost Castle
            </a>
            <button class=”navbar-toggler” type=”button” data-toggle=”collapse” data-target=”#navbarNavAltMarkup” aria-controls=”navbarNavAltMarkup”
             aria-expanded=”false” aria-label=”Toggle navigation”>
                <span class=”navbar-toggler-icon”></span>
            </button>
            <div class=”collapse navbar-collapse justify-content-end” id=”navbarNavAltMarkup”>
                <div class=”navbar-nav”>
                    <a class=”nav-item nav-link active” href=”#”>Login</a>
                    <a class=”nav-item nav-link” href=”/register”>Sign Up</a>
                </div>
            </div>
        </nav>
        <div class=”login row justify-content-md-center”>
            <div class=”col-md-8″>
                <div class=”card border-secondary”>
                    <div class=”card-header”>
                        Login
                    </div>
                    <div class=”card-body text-secondary”>
                        <form id=”login” onsubmit=”return login();”>
                            <div class=”form-group row”>
                                <label for=”name” class=”col-sm-4 text-right”>Name</label>
                                <div class=”col-sm-6″>
                                    <input type=”text” name=”name” class=”form-control” id=”name” placeholder=”Name” required>
                                </div>
                            </div>
                            <div class=”form-group row”>
                                <label for=”password” class=”col-sm-4 text-right”>Password</label>
                                <div class=”col-sm-6″>
                                    <input type=”password” name=”password” class=”form-control” id=”password” placeholder=”Password” required>
                                </div>
                            </div>
                            <div class=”form-check row”>
                                <div class=”col-sm-8 ml-sm-auto”>
                                    <label class=”custom-control custom-checkbox mb-2 mr-sm-2 mb-sm-0″>
                                        <input type=”checkbox” class=”custom-control-input”>
                                        <span class=”custom-control-indicator”></span>
                                        <span class=”custom-control-description”>Remember me</span>
                                    </label>
                                </div>
                            </div>
                            <div class=”row”>
                                <div class=”col-sm-8 ml-sm-auto”>
                                    <button type=”submit” class=”btn btn-dark” id=”loginBtn”>
                                        <i class=”fa fa-sign-in” aria-hidden=”true”></i> LOGIN
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script src=”/js/jquery.js”></script>
    <script src=”/js/popper.min.js”></script>
    <script src=”/js/bootstrap.min.js”></script>
    <script src=”/js/jquery.md5.js”></script>
    <script>
        function login() {
            var name = $(‘input[name=name]’).val();
            var pwd = $(‘input[name=password]’).val();
            var param = {
                name: name,
                password: $.md5(pwd)
            };
            $.ajax({
                type: ‘post’,
                url: ‘/ghost/login’,
                data: param,
                dataType: ‘json’,
                success: function (res) {
                    alert(res.errorMsg);
                },
                error: function (err) {
                    console.log(err);
                }
            });
            return false;
        }
    </script>
</body>
</html>

signUp.html:
html 代码

<!DOCTYPE html>
<html lang=”en”>
<head>
    <meta charset=”UTF-8″>
    <meta name=”keywords” content=”your keywords”>
    <meta name=”description” content=”your description”>
    <meta name=”author” content=”author,email address”>
    <meta name=”robots” content=”index,follow”>
    <meta http-equiv=”X-UA-Compatible” content=”IE=Edge,chrome=1″>
    <meta name=”renderer” content=”ie-stand”>
    <title>Register</title>
    <link rel=”stylesheet” href=”/css/bootstrap.css”>
    <link rel=”stylesheet” href=”/css/font-awesome.css”>
    <link rel=”stylesheet” href=”/css/style.css”>
</head>
<body>
    <div class=”containers”>
        <nav class=”navbar navbar-expand-md navbar-dark bg-dark”>
            <a class=”navbar-brand” href=”#”>
                <i class=”fa fa-fort-awesome” aria-hidden=”true”></i> Ghost Castle
            </a>
            <button class=”navbar-toggler” type=”button” data-toggle=”collapse” data-target=”#navbarNavAltMarkup” aria-controls=”navbarNavAltMarkup”
             aria-expanded=”false” aria-label=”Toggle navigation”>
                <span class=”navbar-toggler-icon”></span>
            </button>
            <div class=”collapse navbar-collapse justify-content-end” id=”navbarNavAltMarkup”>
                <div class=”navbar-nav”>
                    <a class=”nav-item nav-link” href=”/login”>Login</a>
                    <a class=”nav-item nav-link active” href=”#”>Sign Up</a>
                </div>
            </div>
        </nav>
        <div class=”login row justify-content-md-center”>
            <div class=”col-md-8″>
                <div class=”card border-secondary”>
                    <div class=”card-header”>
                        Register
                    </div>
                    <div class=”card-body text-secondary”>
                        <form onsubmit=”return register();”>
                            <div class=”form-group row”>
                                <label for=”name” class=”col-sm-4 text-right”>Name</label>
                                <div class=”col-sm-6″>
                                    <input type=”text” name=”name” class=”form-control” id=”name” placeholder=”Name” required>
                                </div>
                            </div>
                            <div class=”form-group row”>
                                <label for=”name” class=”col-sm-4 text-right”>Sex</label>
                                <div class=”col-sm-6″>
                                    <label class=”custom-control custom-radio”>
                                        <input id=”radioStacked1″ name=”sex” type=”radio” value=”0″ class=”custom-control-input” required>
                                        <span class=”custom-control-indicator”></span>
                                        <span class=”custom-control-description”>Male</span>
                                    </label>
                                    <label class=”custom-control custom-radio”>
                                        <input id=”radioStacked2″ name=”sex” type=”radio” value=”1″ class=”custom-control-input” required>
                                        <span class=”custom-control-indicator”></span>
                                        <span class=”custom-control-description”>Female</span>
                                    </label>
                                </div>
                            </div>
                            <div class=”form-group row”>
                                <label for=”address” class=”col-sm-4 text-right”>Address</label>
                                <div class=”col-sm-6″>
                                    <input type=”text” name=”address” class=”form-control” id=”address” placeholder=”Address” required>
                                </div>
                            </div>
                            <div class=”form-group row”>
                                <label for=”password” class=”col-sm-4 text-right”>Password</label>
                                <div class=”col-sm-6″>
                                    <input type=”password” name=”password” class=”form-control” id=”password” placeholder=”Password” required>
                                </div>
                            </div>
                            <div class=”form-group row”>
                                <label for=”password_confirmation” class=”col-sm-4 text-right”>Confirm Password</label>
                                <div class=”col-sm-6″>
                                    <input type=”password” name=”password_confirmation” class=”form-control” id=”password_confirmation”
                                     placeholder=”Confirm Password” required>
                                </div>
                            </div>
                            <div class=”row”>
                                <div class=”col-sm-8 ml-sm-auto”>
                                    <button type=”submit” class=”btn btn-dark”>
                                        <i class=”fa fa-sign-in” aria-hidden=”true”></i> Sign Up
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script src=”/js/jquery.js”></script>
    <script src=”/js/popper.min.js”></script>
    <script src=”/js/bootstrap.min.js”></script>
    <script src=”/js/jquery.md5.js”></script>
    <script>
        function register() {
            var name = $(‘input[name=name]’).val();
            var pwd = $.md5($(‘input[name=password]’).val());
            var cpwd = $.md5($(‘input[name=password_confirmation]’).val());
            var sex = $(‘input[name=sex]:checked’).val();
            var address = $(‘input[name=address]’).val();
            var udate = new Date();
            udate = udate.Format(‘yyyy-MM-dd hh:mm:ss’);
            if (pwd != cpwd) {
                alert(‘The confirmation password is not identical.’);
                return false;
            }
            var param = {
                uname: name,
                upwd: pwd,
                usex: sex,
                uaddress: address,
                udate: udate
            };
            $.ajax({
                type: ‘post’,
                url: ‘/ghost/register’,
                data: param,
                dataType: ‘json’,
                success: function (res) {
                    alert(‘Register Success’);
                    window.location.href = ‘/’;
                },
                error: function (err) {
                    console.log(err);
                }
            });
            return false;
        }
        // 对Date的扩展,将 Date 转化为指定格式的String
        // 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,
        // 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
        // 例子:
        // (new Date()).Format(“yyyy-MM-dd hh:mm:ss.S”) ==> 2006-07-02 08:09:04.423
        // (new Date()).Format(“yyyy-M-d h:m:s.S”) ==> 2006-7-2 8:9:4.18
        Date.prototype.Format = function (fmt) { //author: meizz
            var o = {
                “M+”: this.getMonth() + 1, //月份
                “d+”: this.getDate(), //日
                “h+”: this.getHours(), //小时
                “m+”: this.getMinutes(), //分
                “s+”: this.getSeconds(), //秒
                “q+”: Math.floor((this.getMonth() + 3) / 3), //季度
                “S”: this.getMilliseconds() //毫秒
            };
            if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + “”).substr(4 – RegExp.$1.length));
            for (var k in o)
                if (new RegExp(“(” + k + “)”).test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : ((“00” + o[k]).substr((“” + o[k]).length)));
            return fmt;
        }
    </script>
</body>
</html>

在cmd中输入启动命令:node app.js
地址栏输入: https://www.rokub.com:3001
若未登录,则跳转到登录页面:https://www.rokub.com:3001/login

web前端开发个人技能 前端开发必会的技能 前端开发专业技能

» 本文来自:前端开发者 » 《node.js入门实现注册及登录》
» 本文链接地址:https://www.rokub.com/6120.html
» 您也可以订阅本站:https://www.rokub.com
赞(0)
64K

评论 抢沙发

评论前必须登录!