Title

MySQL之旅(5) node.js + express + mysql 实现简单的登录注册

导言:具体相关信息在前几章有写,这次我直接黏贴代码,代码有相关注释

服务 app.js

// 1. 导入http模块
var http = require('http');
// 2. 导入文件模块
var fs = require('fs');
// 3. 导入路径模块
var path = require('path');
// 4. 导入url模块(用来解析get请求参数)
var url = require('url');
// 5. 导入querystring模块(用来解析post请求参数)
var querystring = require('querystring');

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');


var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

/**
 * 连接 MySQL 数据库
 * */ 
var mysql = require('mysql');
var connection = mysql.createConnection({
  host:'127.0.0.1',
  user: 'root',
  password: '123',
  database: 'userslist',
  port: '3306'
});
connection.connect((err) => {
  if(err) throw err;
  console.log(`连接成功`)
});

var app = express();

// 跨域
const cors = require( 'cors');
app.use(cors());

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// 登录接口
app.post('/api/login',(req, res) => {
  let sql = `SELECT * FROM person WHERE name = ?`, name = req.body.name, passworld = req.body.passworld;
  // 检测 数据库 是否存在
  connection.query(sql, [name], function (error, results, fields) { 
    if(error) throw error;
    if(results.length >= 1){
      if(passworld == results[0].passworld){
        res.json({code: 10000, message: `登录成功`});
      }else{
        res.json({code: 10001, message: `密码错误`});
      }
    }else{
      res.json({code: 40004, message: `此用户未注册`})
    }
   })
});
// 注册接口
app.post(`/api/register`, (req, res) => {
  let sql = `INSERT INTO person(number,name,passworld,birthday,age,member_id,cardID,phone,address, email) VALUES (?,?,?,?,?,?,?,?,?,?)`, resql = `SELECT * FROM person WHERE name = ?`;
  let { number,name,passworld,birthday,age,member_id,cardID,phone,address, email} = req.body;
  console.log(`dataBig:`,req.body);
  connection.query(resql, [name], (error, results, fields) => {
    console.log(`results:`,results)
    if(error) throw error;
    if(results.length >= 1){
      res.json({code: 10002, message: `用户名已存在`})
    }else{
      connection.query(sql, [number,name,passworld,birthday,age,member_id,cardID,phone,address, email], (error, results, fields) => {
        if (error) throw error;
        console.log(`results:`,results)
        if(results.affectedRows == 1){
          res.json({code: 20000, message: `注册成功`})
        }else{
          res.json({code: 20001, message: `注册失败`})
        }
      })
    }
  })
})
app.get('/checkMysql', (req, res) => {
  let sql = `SELECT * FROM person`;
  connection.query(sql, (err, result) => {
    if(err){
      console.log(err);
      res.send(`<p>err:${err}</p>`)
    }else{
      console.log(result);
      res.json(result)
    }
  })
});
// 设置端口
app.listen(3434, console.log("application is start at port 3434"));

module.exports = app;
    

html  页面

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录/注册</title>
    <script src="../javascripts/common/jq-3.60-min.js"></script>
    <link rel="stylesheet" href="./../stylesheets/common/css/common.css">
    <style>
        .login_and_register{
            width: 500px;
            margin: 200px auto;
            position: relative;
            perspective: 1000px;
        }
        .login_wrap {
            width: 500px;
            height: auto;
            background-color: transparent;
            border-radius: 10px;
            border: 1px solid #f5f5f5;
            padding: 20px;
            box-shadow: 0px 0px 10px 1px white;
        }

        .longin_item {
            text-align: center;
            line-height: 100px;
            border-bottom: 1px solid #f5f5f5;
            color: white;
        }

        .longin_item span {
            padding-right: 20px;
        }

        .longin_item input {
            border: 1px dashed;
            background-color: transparent;
            color: white;
            height: 50px;
            width: 350px;
            padding-left: 20px;
            
        }

        .login_button {
            height: 100px;
        }

        #login {
            color: blue;
            text-align: center;
            font-size: 24px;
            text-shadow: 0 1px 10px #f5f5f5;
        }

        #register {
            color: red;
            text-align: center;
            font-size: 24px;
            text-shadow: 0 1px 10px #f5f5f5;
        }

        #back_login {
            color: green;
            text-align: center;
            font-size: 24px;
            text-shadow: 0 1px 10px #f5f5f5;
        }
        .active{
            transition: 1s;
            transform-style: preserve-3d;
        }
        #login_view{
            position: absolute;
        }
        #register_view{
            position: absolute;
        }
    </style>
</head>

<body style="height: 100%; overflow: hidden;" class="flex_col">
    <div class="login_and_register">
        <!-- 登录界面 -->
        <div id="login_view" class="login_wrap active" style="display: block;">
            <div class="login_main flex_col">
                <div class="longin_item flex_row flex_between">
                    <span>登录账号:</span><input type="text" id="account" placeholder="请输入你即将登录的账号" />
                </div>
                <div class="longin_item flex_row flex_between">
                    <span>登录密码:</span><input type="password" id="psw" placeholder="请输入您的密码" />
                </div>
            </div>
            <div class="login_button flex_row flex_between">
                <div id="login" onclick="login()" class="login">登录</div>
                <div id="register" class="register" onclick="flip('register_view')">注册</div>
            </div>
        </div>
        <!-- 注册界面 -->
        <div id="register_view" class="login_wrap active" style="display: none;">
            <div class="login_main flex_col">
                <div class="longin_item flex_row flex_between">
                    <span>注册账号:</span><input type="text" id="register_account" placeholder="请输入你即将注册的账号" />
                </div>
                <div class="longin_item flex_row flex_between">
                    <span>电话号码:</span><input type="text" id="phone" placeholder="请输入你即将注册的电话号码" />
                </div>
                <div class="longin_item flex_row flex_between">
                    <span>常用邮箱:</span><input type="text" id="email" placeholder="请输入你即将注册的常用邮箱" />
                </div>
                <div class="longin_item flex_row flex_between">
                    <span>设置密码:</span><input type="password" id="passworld" placeholder="请设置您的密码" />
                </div>
            </div>
            <div class="login_button flex_row flex_around">
                <div id="login" class="login register_button" onclick="register()">注册</div>
                <div id="register" class="register register_login_button">注册并登录</div>
                <div id="back_login" onclick="flip('login_view')">返回</div>
            </div>
        </div>
    </div>
    <script>
        // 切换
        function flip(event) {
            let loginView = document.querySelector(`#login_view`);
            let registerView = document.querySelector(`#register_view`);
            if(event == `login_view`){
                if(loginView.style.transform == `rotateY(360deg)`){
                    loginView.style.transform = `rotateY(0deg)`;
                }else{
                    loginView.style.transform = `rotateY(360deg)`;
                }
                loginView.style.display = `block`;
                registerView.style.display = `none`;
            } else{
                if(registerView.style.transform == `rotateY(360deg)`){
                    registerView.style.transform = `rotateY(0deg)`;
                }else{
                    registerView.style.transform = `rotateY(360deg)`;
                }
                registerView.style.display = `block`;
                loginView.style.display = `none`;
            }
        };
        // 登录
        function login() { 
            console.log(11111)
            let login = document.querySelector(`#login`);
            let account = document.querySelector(`#account`).value;
            let psw = document.querySelector(`#psw`).value;
            if(!account){
                alert(`空账号`)
            }else if(!psw){
                alert(`密码为空`)
            }else{
                let data = {name: account, passworld: psw};
                $.post(`http://127.0.0.1:3434/api/login`,data, (r) => {
                    alert(r.message)
                })
            }
         };
         function register() { 
             let account = document.querySelector(`#register_account`).value, phone = document.querySelector(`#phone`).value, email = document.querySelector(`#email`).value, passworld = document.querySelector(`#passworld`).value;
             let number = '5', birthday = `2021-06-29`, age = '20', member_id = '5',  cardID = `456313`, address = `748300`;
             if(!account){
                 alert(`注册账号不能为空`);
             }else if(!phone){
                 alert(`注册电话号码不能为空`);
             }else if(!email){
                 alert(`注册E-mail不能为空`);
             }else if(!passworld){
                 alert(`注册密码不能为空`);
             }else{
                 let data = {number,name:account,passworld,birthday,age,member_id,cardID,phone,address, email};
                 $.post(`http://127.0.0.1:3434/api/register`, data, (r) => {
                     alert(r.message);
                 })
             }
          }
    </script>
</body>
   
</html>

效果图如下:

posted @ 2021-06-29 19:11  谈亦行  阅读(487)  评论(1编辑  收藏  举报