使用Node连接MySql数据库展示登录、注册demo

一、安装Mysql数据库(选择mysql服务建议选5.7)

        参考连接:https://www.cnblogs.com/tusens/p/18162502 

        可安装数据库可视化工具比如:DBerver

二、安装Node

        参考连接:手把手教你用node.js搭建一个Web服务_node.js_脚本之家

三、登录、注册demo 

使用到的依赖包:cors、express、mysql、mysql2

启动MySql命令:net start mysql57(数据库名称)

启动node项目命令: node server 

1.创建mysql.config.js文件(mysql数据库配置)
module.exports = {
        host: 'localhost',//主机地址
        user: 'root',//数据库用户名
        password: '88888888',//密码
        database: 'user',//数据库名
        port: '3306',//端口
        multipleStatements: true, //设置一次请求允许多条sql语句同时执行。默认false
    
}
2.创建mysql.js文件(数据库链接)
// 使用引入mysql2
const mysql = require('mysql2')
//引入mysql配置文件
const mysqlConfig = require('./mysql.config')
module.exports = {
    query: function (sql, params, callback) {
        //每次使用的时候都有创建链接,数据操作完成之后关闭链接
        const connection = mysql.createConnection(mysqlConfig)
        connection.connect(function (err) {
            if (err) {
                console.log('数据库链接失败---11');
                throw err
            }else{
                console.log('数据库连接成功---11');
            }
            //执行数据操作

            connection.query(sql, params, function (err, results, fields) {
                if (err) {
                    console.log('数据库链接失败---22');
                    throw err
                }else{
                    console.log('数据库链接成功---22');
                }

                //将查询出来的数据返回给回调函数
                callback && callback(
                    results ? JSON.parse(JSON.stringify(results)) : null,
                    fields ? JSON.parse(JSON.stringify(fields)) : null
                )

                //停止链接数据库,必须在查询语句后,不然一调用这个方法,就直接停止连接,数据操作就会失败
                connection.end(function (err) {
                    if (err) {
                        console.log('关闭数据库链接失败');
                        throw err
                    }else{
                        console.log('关闭数据库链接成功');
                    }
                })
            })



        })
    }
}



3.创建server.js文件,使用Node连接MySql数据库
//  设置服务器端口
const PORT = 33066;
// 引入mysql模块
const mysql = require('mysql')
const db = require('./mysql')
const bodyparser = require('body-parser')
const express = require('express')// 引入Express模块 
const cors = require('cors')
const app = express(); // 创建Express应用程序实例  

app.use(bodyparser.json());
app.use(bodyparser.urlencoded({
    extended: false
}))

// 解决跨越
app.use(cors())


// 登录实例
app.post('/login', function(req, res, next) {
    let queryString = "SELECT id,name,passWord FROM account WHERE name=" + mysql.escape(req.body.name);
    db.query(queryString, function(err, rows) {
        if(err) {
            res.json(err);
        } else {
            if(rows.length == 0) {
                res.json({
                    code: '0',
                    msg: '用户不存在'
                });
            } else if(rows[0].passWord == req.body.passWord) {
                res.json(rows);
            } else {
                res.json({
                    code: '1',
                    msg: '密码错误'
                });
            }
        }
    })
});

// 注册
app.post('/add', function(req, res, next) {
    let queryString = "SELECT id,name,passWord FROM account WHERE name=" + mysql.escape(req.body.name);
    let addString = "INSERT INTO account(name,passWord) VALUES(?,?)";
    let addSqlParams = [req.body.name, req.body.passWord];
    db.query(queryString, function(err, rows) {
        if(err) {
            res.json(err);
        } else {
            if(rows.length != 0) {
                res.json({
                    code: '0',
                    msg: '用户已经存在'
                });
            } else {
                db.query(addString, addSqlParams, function(err, rows) {
                    res.json({
                        code: '1',
                        msg: '注册成功'
                    });
                })
            }
        }
    })
});

// 查询所有用户信息
app.post('/select', function(req, res, next) {
    let queryString = "SELECT id,name,passWord FROM account";
    db.query(queryString, function(err, rows) {
        if(err) {
            res.json(err);
        } else {
            res.json({
                code: "1",
                msg: rows,
                login_id: req.body.id
            });
        }
    })
});

// 删除某个用户
app.post('/del', function(req, res, next) {
    let queryString = "DELETE FROM account WHERE id = " + mysql.escape(req.body.id);
    if(req.body.id != req.body.login_id) {
        db.query(queryString, function(err, rows) {
            if(err) {
                res.json(err);
            } else {
                res.json({
                    code: '1',
                    msg: '删除成功'
                });
            }
        })
    } else {
        res.json({
            code: '0',
            msg: '不能自己删除自己'
        });
    }
});

// 只能修改自己的密码
app.post('/upd', function(req, res, next) {
    let queryString = 'UPDATE account SET `passWord` = ? WHERE id = ?';
    let updSqlParams = [req.body.passWord, req.body.id];
    if(req.body.id == req.body.login_id) {
        db.query(queryString, updSqlParams, function(err, rows) {
            if(err) {
                if(err.affectedRows == 1) {
                    res.json({
                        code: '1',
                        msg: '修改成功'
                    });
                }else{
                    res.json({
                        code: '0',
                        msg: '只能修改自己的密码'
                    });
                }
            } else {
                res.json(err);
            }
        })
    } else {
        res.json("未知错误");
    }
});




// 监听指定的端口  
app.listen(PORT, (err) => {
    if (!err)
        console.log('服务器启动成功!')
})


4.创建index.html文件
<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8">
        <!-- 设置语言为中文 -->
        <meta http-equiv="Content-Language" content="zh-cn" />
        <!-- 禁止百度转码 -->
        <meta http-equiv="Cache-Control" content="no-siteapp" />
        <!-- 是否开启cleartype显示效果 -->
        <meta http-equiv="cleartype" content="on">
        <meta name="skype_toolbar" content="skype_toolbar_parser_compatible">
        <!-- 优先使用最新的chrome版本 -->
        <meta http-equiv="X-UA-Compatible" content="chrome=1" />
        <!-- 启用360浏览器的极速模式(webkit) -->
        <meta name="renderer" content="webkit">
        <!-- 避免IE使用兼容模式 -->
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <!-- 针对手持设备优化,主要是针对一些老的不识别viewport的浏览器,比如黑莓 -->
        <meta name="HandheldFriendly" content="true">
        <!-- 设置手持设备支持 -->
        <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport" />
        <meta content="yes" name="apple-mobile-web-app-capable">
        <meta content="black" name="apple-mobile-web-app-status-bar-style">
        <meta content="telephone=no" name="format-detection">
        <title></title>
        <style>
            table,
            table tr th,
            table tr td {
                border: 1px solid #0094ff;
            }
        </style>
    </head>

    <body>
        <table>
            <tr>
                <th>编号</th>
                <th>用户名</th>
                <th>密码</th>
                <th>操作</th>
            </tr>
            <tbody id="tbody">

            </tbody>
        </table>
        <a href="register.html">添加用户</a>
        <div id="msg"></div>
    </body>
    <script type="text/javascript"src="http://code.jquery.com/jquery-1.4.1.min.js"></script> 
    <script>
        main();

        function main() {
            let body_id = {
                "id": getQueryValue("id")
            }
            $.ajax({
                type: "POST",
                url: "http://localhost:33066/select",
                contentType: 'application/json',
                // data: JSON.stringify(body_id),
                success: function(data) {
                    console.log('index---',data);
                    let html = '';
                    for(let i = 0; i < data.msg.length; i++) {
                        html += '<tr>' +
                            '<td>' + data.msg[i].id + '</td>' +
                            '<td>' + data.msg[i].name + '</td>' +
                            '<td><input type="text" value='+ data.msg[i].passWord +' id="passWord'+data.msg[i].id+'"/></td>' +
                            '<td>'+
                            '<span style="color:red;" onclick="del(' + data.msg[i].id + ',' + data.login_id + ')">删除</span>'+
                            '<span style="color:blue;" onclick="upd(' + data.msg[i].id + ',' + data.login_id + ')">修改</span>'+
                            '</td>' +
                            '</tr>';
                    }
                    $("#tbody").html(html);
                }
            });
            
        }

        function del(id, login_id) {
            if(id == login_id) {
                alert("不能自己删除自己");
            } else {
                let body_id = {
                    "id": id,
                    "login_id": login_id
                }
                $.ajax({
                    type: "POST",
                    url: "http://localhost:33066/del",
                    contentType: 'application/json',
                    data: JSON.stringify(body_id),
                    success: function(data) {
                        if(data.code == 1) {
                            alert("删除成功");
                            main();
                        } else if(data.code == 0) {
                            alert(data.msg);
                        } else {
                            $("#msg").text(JSON.stringify(data));
                        }
                    }
                });
            }
        }
        
        function upd(id, login_id){
            if(id != login_id) {
                alert("只能修改自己的密码");
            } else {
                let body_id = {
                    "id": id,
                    "login_id": login_id,
                    "passWord": $("#password"+login_id).val().trim()
                }
                $.ajax({
                    type: "POST",
                    url: "http://localhost:33066/upd",
                    contentType: 'application/json',
                    data: JSON.stringify(body_id),
                    success: function(data) {
                        if(data.code == 1) {
                            alert("修改自己的密码成功");
                            main();
                        } else if(data.code == 0) {
                            alert(data.msg);
                        } else {
                            $("#msg").text(JSON.stringify(data));
                        }
                    }
                });
            }
        }

        function getQueryValue(name) {
            // 创建正则表达式,这个表达式匹配以name开头或者&name开头,以&结尾或者就是name结尾
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
            // 解码url
            var decodedUrl = decodeURI(window.location.search);
            // 匹配表达式,返回一个group数组
            var r = decodedUrl.substr(1).match(reg);
            // 数组下标2的元素就是所要截取的结果
            if(r != null) return unescape(r[2]);
            return null;
        }
    </script>

</html>
5.创建login.html文件
<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8">
        <!-- 设置语言为中文 -->
        <meta http-equiv="Content-Language" content="zh-cn" />
        <!-- 禁止百度转码 -->
        <meta http-equiv="Cache-Control" content="no-siteapp" />
        <!-- 是否开启cleartype显示效果 -->
        <meta http-equiv="cleartype" content="on">
        <meta name="skype_toolbar" content="skype_toolbar_parser_compatible">
        <!-- 优先使用最新的chrome版本 -->
        <meta http-equiv="X-UA-Compatible" content="chrome=1" />
        <!-- 启用360浏览器的极速模式(webkit) -->
        <meta name="renderer" content="webkit">
        <!-- 避免IE使用兼容模式 -->
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <!-- 针对手持设备优化,主要是针对一些老的不识别viewport的浏览器,比如黑莓 -->
        <meta name="HandheldFriendly" content="true">
        <!-- 设置手持设备支持 -->
        <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport" />
        <meta content="yes" name="apple-mobile-web-app-capable">
        <meta content="black" name="apple-mobile-web-app-status-bar-style">
        <meta content="telephone=no" name="format-detection">
        <title></title>
    </head>

    <body>
        用户名:<input type="text" maxlength="16" id="name" /> 密码:
        <input type="password" maxlength="16" id="passWord" />
        <button onclick="login()">登录</button>
        <div id="msg"></div>
        <div id="reg"></div>
    </body>
    <script type="text/javascript"src="http://code.jquery.com/jquery-1.4.1.min.js"></script> 
    <script>
        function login() {
            let name = $("#name").val().trim();
            let passWord = $("#passWord").val().trim();
            if(!name) {
                alert("用户名不能为空");
                return false;
            }
            if(!passWord) {
                alert("密码不能为空");
                return false;
            }
            let loginReqbody = {
                'name': name,
                'passWord': passWord
            }
            $.ajax({
                type: "POST",
                url: "http://localhost:33066/login",
                contentType: 'application/json',
                data: JSON.stringify(loginReqbody),
                success: function(data) {
                    $("#passWord").val("");
                    if(data.code == 0) {
                        $("#msg").text(data.msg).css("color", "red");
                        $("#reg").html("<a href='register.html'>前往注册</a>").css("color", "blue");
                    } else if(data.code == 1) {
                        $("#msg").text(data.msg).css("color", "red");
                    } else if(data[0].name || data[0].passWord) {
                        alert("登录成功");
                        window.location.href = 'index.html?id=' + data[0].id;
                    } else {
                        $("#msg").text(JSON.stringify(data));
                    }
                }
            });
        }
    </script>

</html>
6.创建register.html文件
<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8">
        <!-- 设置语言为中文 -->
        <meta http-equiv="Content-Language" content="zh-cn" />
        <!-- 禁止百度转码 -->
        <meta http-equiv="Cache-Control" content="no-siteapp" />
        <!-- 是否开启cleartype显示效果 -->
        <meta http-equiv="cleartype" content="on">
        <meta name="skype_toolbar" content="skype_toolbar_parser_compatible">
        <!-- 优先使用最新的chrome版本 -->
        <meta http-equiv="X-UA-Compatible" content="chrome=1" />
        <!-- 启用360浏览器的极速模式(webkit) -->
        <meta name="renderer" content="webkit">
        <!-- 避免IE使用兼容模式 -->
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <!-- 针对手持设备优化,主要是针对一些老的不识别viewport的浏览器,比如黑莓 -->
        <meta name="HandheldFriendly" content="true">
        <!-- 设置手持设备支持 -->
        <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport" />
        <meta content="yes" name="apple-mobile-web-app-capable">
        <meta content="black" name="apple-mobile-web-app-status-bar-style">
        <meta content="telephone=no" name="format-detection">
        <title></title>
    </head>

    <body>
        用户名:<input type="text" maxlength="16" id="name" /> 密码:
        <input type="password" maxlength="16" id="passWord" />
        <button onclick="register()">注册</button>
        <div id="msg"></div>
    </body>
    <script type="text/javascript"src="http://code.jquery.com/jquery-1.4.1.min.js"></script> 
    <script>
        function register() {
            let name = $("#name").val().trim();
            let passWord = $("#passWord").val().trim();
            if(!name) {
                alert("用户名不能为空");
                return false;
            }
            if(!passWord) {
                alert("密码不能为空");
                return false;
            }
            let loginReqbody = {
                'name': name,
                'passWord': passWord
            }
            $.ajax({
                type: "POST",
                url: "http://localhost:33066/add",
                contentType: 'application/json',
                data: JSON.stringify(loginReqbody),
                success: function(data) {
                    if(data.code == 0) {
                        $("#msg").text(data.msg).css("color", "red");
                        $("#passWord").val("");
                    } else if(data.code == 1) {
                        alert("注册成功");
                        window.location.href = 'login.html';
                    } else {
                        $("#msg").text(JSON.stringify(data));
                    }
                }
            });
        }
    </script>

</html>

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值