前端(jquery)+ 后端(Node.js)+ 数据库(mysql)实现后台管理系统

总体预览

  1. 登录页面
    请添加图片描述

  2. 注册页面

请添加图片描述

  1. 主界面

请添加图片描述

  1. 文件夹
    请添加图片描述

前端代码

  1. 登录页面web/signin.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>Document</title>
    <style>
        form{
      
      
            width: 500px;
            height: 500px;
            border-color: pink;
            margin: 0 auto;
        }
        input{
      
      
            width: 200px;
            height: 30px;
            margin-top: 10px;
            outline: none;
        }
        input:last-child{
      
      
            margin-top: 27px;
        }
    </style>
</head>
<body>
    <form>
        <input type="text" name="name" placeholder="输入名字"><br>
        <p class="nameTip"></p>
        <input type="password" name="password" placeholder="输入密码"><br>
        <p class="passwordTip"></p>
        <input type="submit" name="submit" value="登录"><br>
        <input type="button" name="login" value="注册">
    </form>
    <script src="jquery.js"></script>
    <script>
        const nameVal=$('input[name="name"]').val()
        const passwordVal=$('input[name="password"]').val()
        //表单非空验证
        function checkUserNameNull(){
      
      
            if($('input[name="name"]').val()==''){
      
      
                $('.nameTip').html('用户名不能为空')
                return false
            }else{
      
      
                return checkUserName()
            }
        }
        function checkPasswordNull(){
      
      
            if($('input[name="password"]').val()==''){
      
      
                $('.passwordTip').html('密码不能为空')
            }else{
      
      
                return checkPassword()
            }
        }

        //表单强度验证
        function checkUserName(){
      
      
            const reg=/[0-9a-zA-Z]{4,10}/
            if(reg.test($('input[name="name"]').val())){
      
      
                $('.nameTip').html('')
                return true
            }else{
      
      
                $('.nameTip').html('不符合英文加数字,长度在4-10规则')
                return false
            }
        }
        function checkPassword(){
      
      
            const reg=/\w/
            if(reg.test($('input[name="password"]').val())){
      
      
                $('.passwordTip').html('')
                return true
            }else{
      
      
                $('.passwordTip').html('不符合英文加数字')
                return false
            }
        }

        //失去焦点时验证
        $('form').on('blur','input[name="name"]',function(){
      
      
            checkUserNameNull()
        }).on('blur','input[name="password"]',function(){
      
      
            checkPasswordNull()
        })

		//提交时执行
        $('form').on('submit',function(e){
      
      
            e.preventDefault()
            //是否符合条件
            const isokName=checkUserNameNull()
            const isokPasswors=checkPasswordNull()

			if(isokName || isokPasswors){
      
      
				 $.ajax({
      
      
                url:'http://10.7.178.116:4000/api/sign',
                type:'post',
                data:{
      
      
                    username:$('input[name="name"]').val(),
                    password:$('input[name="password"]').val()
                },
                success:function(data){
      
      
                    if(data.status==1){
      
      
                        alert(data.message)
                        
                    }else{
      
      
                        localStorage.setItem('token',JSON.stringify(data.token))
                        alert('登录成功')
                        location.href='index.html'
                    }
                }
            })
        }).on('click','input[name="login"]',function(){
      
      
            location.href='login.html'
        })
	}
           
    </script>
</body>
</html>
  1. 注册页面web/login.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>Document</title>
    <style>
        form{
      
      
            width: 500px;
            height: 500px;
            border-color: pink;
            margin: 0 auto;
        }
        input{
      
      
            width: 200px;
            height: 30px;
            margin-top: 10px;
            outline: none;
        }
    </style>
</head>
<body>
    <form>
        <input type="text" name="name" placeholder="输入名字"><br>
        <input type="password" name="password" placeholder="输入密码"><br>
        <input type="button" name="login" value="注册">
    </form>
    <script src="jquery.js"></script>
    <script>
    	//点击注册时执行
         $('form').on('click','input[name="login"]',function(e){
      
      
            e.preventDefault()
            $.ajax({
      
      
                url:'http://10.7.178.116:4000/api/reguser',
                type:'post',
                data:{
      
      
                    username:$('input[name="name"]').val(),
                    password:$('input[name="password"]').val()
                },
                success:function(data){
      
      
                    if(data.status==1){
      
      
                        alert(data.message)
                    }else{
      
      
                    	//成功跳转到登录页面
                        location.href='signin.html'
                    }
                }
            })
        })
    </script>
</body>
</html>
  1. 主界面web/index.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>Document</title>
    <style>
        body,html{
      
      
            height: 100%;
        }
        *{
      
      
            margin: 0;
            padding: 0;
        }
        .head{
      
      
            width: 100%;
            height: 150px;
            background-color: skyblue;
        }
        .head img{
      
      
            width: 100px;
            height: 100px;
            border-radius: 50%;
            margin-left: 20px;
            margin-top: 10px;
        }
        .head .use{
      
      
            float: left;
        }
        .head div{
      
      
            font-size: 24px;
            margin-left: 28px;
           
        }
        .head button{
      
      
            width: 50px;
            height: 50px;
            float: right;
            margin-right: 20px;
            margin-top: 50px;
        }
        .nav{
      
      
            width: 200px;
            height: 100%;
            background-color: pink;
            float: left;
        }
        .nav .title{
      
      
            height: 30px;
            padding: 10px 0;
            margin-left: 15px;
            color: #fff;
            line-height: 30px;
        }
        .nav li{
      
      
            list-style: none;
            padding-left: 20px;
            color: #fff;
            height: 30px;
        }
        .nav .active{
      
      
            background-color: blueviolet;
        }
        .table{
      
      
          
            height: 100%;
            margin-left:200px ;
            background-color: bisque;
        }
        .table table{
      
      
            text-align: center;
            line-height: 100px;
            width: 100%;
            
        }
        .table table img{
      
      
            width: 80px;
            height: 80px;
        }
        .table table tr td{
      
      
            width: 100px;
            height: 100px;
        }
        .table form{
      
      
            width: 300px;
            margin: 0 auto;
            text-align: center;
        }
        .table input{
      
      
            margin-top: 10px;
            outline: none;
        }
        .table button{
      
      
            margin-top: 10px;
            width: 40px;
        }
    </style>
</head>
<body>
    <div class="head">
        <div class="use"></div>
        <button class="signOut">退出</button>
    </div>
    <div class="nav">
        <div class="title">管理</div>
            <ul>
                <li class="vister">游客列表</li>
                <li class="updataPws">更新信息</li>
                <li class="avatar">重置头像</li>
                <li class="password">重置密码</li>
            </ul>
    </div>
    <div class="table"></div>
    
    <script src="jquery.js"></script>
    <script>
        //获取用户信息
        const token=JSON.parse(localStorage.getItem('token')) 
        function fun(){
      
      
            $.ajax({
      
      
                url:'http://10.7.178.116:4000/my/userinfo',
                type:'get',
                headers: {
      
      'Authorization': token},
                dataType: 'JSON',
                success:function(data){
      
      
                    if(data.status==1){
      
      
                        alert('获取信息失败')
                    }else{
      
      
                        data=data.data
                        let str=`
                        <img src="${ 
        data.user_pic}">
                        <div>${ 
        data.username}</div>
                         `
                        $('.use').html(str)
                        
                    }
                }
            })
        }
        fun()

		//右边页面动画
        function animation(){
      
      
            $('.nav .title').click(function(){
      
      
                $(this).next().slideToggle()
            })
            $('.nav li').click(function(){
      
      
                $('.nav li').removeClass('active')
                $(this).addClass('active')
            })
        }
        animation()

         //右边功能按钮
        function total(){
      
      
            $('.nav').on('click','.vister',function(){
      
      
                getList()
            }).on('click','.updataPws',function(){
      
      
                getUpdataPws()
            }).on('click','.avatar',function(){
      
      
                getAvatar()
            }).on('click','.password',function(){
      
      
                getPassword()
            })
            
            
            //退出按钮
            $('.head').on('click','.signOut',function(){
      
      
            	//清空密钥
                localStorage.setItem('token','')
                location.href='signin.html'
            })
            
        }
        total()
		//获取用户资料
        function getList(){
      
      
                $.ajax({
      
      
                type:'get',
                url:'http://10.7.178.116:4000/my/list',
                headers: {
      
      'Authorization': token},
                dataType: 'JSON',
                success:function(data){
      
      
                    if(status==0){
      
      
                        let list=data.data
                        let strTable=`
                        <table>
                        <tr>
                        <td>id</td>
                        <td>名字</td>
                        <td>图片</td>
                        <td>邮箱</td>
                        <td>功能</td>
                        </tr>
                            `
                       let str=list.map(item=>{
      
      
                            return    `<tr>
                                    <td>${ 
        item.id}</td>
                                    <td>${ 
        item.username}</td>
                                    <td><img src="${ 
        item.user_pic}"></td>
                                    <td>${ 
        item.email}</td>
                                    <td class="del" data-index="${ 
        item.id}">删除</td>
                                    </tr>
                                        `
                        })  
                        str=str.join('')
                        $('.table').html(strTable+str+'</table>')
                    }
                }
                })
                
            }
            //更新用户信息
           function getUpdataPws(){
      
      
                let str=`
                <input type="text" name="id" placeholder="输入id"><br>
                <input type="text" name="nickname" placeholder="输入昵称"><br>
                <input type="text" name="email" placeholder="输入email"><br>
                <input type="button" name="btn" value="提交">
                `
                $('.table').html(str)
                $('input[name="btn"]').on('click',function(){
      
      
                    $.ajax({
      
      
                    type:'post',
                    url:'http://10.7.178.116:4000/my/updateUserinfo',
                    headers: {
      
      'Authorization': token},
                    dataType: 'JSON',
                    data:{
      
      
                        id:$('input[name="id"]').val(),
                        nickname:$('input[name="nickname"]').val(),
                        email:$('input[name="email"]').val(),
                    },
                    success:function(data){
      
      
                        if(data.status==0){
      
      
                            alert('更新信息成功')
                            getList()
                        }
                    }
                    })
                })   
                
           }
            //更改头像
           function getAvatar(){
      
      
               let str=`
                <input type="text" name="avatar" placeholder="输入头像地址"><br>
                <input type="button" name="btn" value="提交">
               `
               $('.table').html(str)
               $('input[name="btn"]').on('click',function(){
      
      
                   $.ajax({
      
      
                    type:'post',
                    url:'http://10.7.178.116:4000/my/update/avatar',
                    headers: {
      
      'Authorization': token},
                    dataType: 'JSON',
                    data:{
      
      
                        avatar:$('input[name="avatar"]').val(),
                    },
                    success:function(data){
      
      
                        console.log(data);
                        if(data.status==0){
      
      
                            alert('更换成功')
                            getList()
                        }
                    }
                   })
               })
           }
           //更换密码
           function getPassword(){
      
      
            let str=`
                <input type="password" name="oldPas" placeholder="输入旧密码"><br>
                <input type="text" name="newPas" placeholder="输入新密码"><br>
                <input type="button" name="btn" value="提交">
               `
            $('.table').html(str)
            $('input[name="btn"]').on('click',function(){
      
      
                $.ajax({
      
      
                    type:'post',
                    url:'http://127.0.0.1:4000/my/updatePwd',
                    headers: {
      
      'Authorization': token},
                    dataType: 'JSON',
                    data:{
      
      
                        oldPws:$('input[name="oldPas"]').val(),
        
                        newPws:$('input[name="newPas"]').val(),
                    },
                    success:function(data){
      
      
                        if(data.status==0){
      
      
                            alert('更改成功')
                            getList()
                        }
                    }
                })
            })
           }
			//删除用户
           $('.table').on('click','.del',function(){
      
      
               const id=$(this).attr('data-index')
               $.ajax({
      
      
                type:'post',
                    url:'http://127.0.0.1:4000/my/delUser',
                    headers: {
      
      'Authorization': token},
                    dataType: 'JSON',
                    data:{
      
      
                        id:id,
                    },
                    success:function(data){
      
      
                        if(data.status==0){
      
      
                            alert('删除成功')
                            getList()
                        }
                    }
               })
           })
    </script>
</body>
</html>

后端

  1. 连接数据库db/index.js
const mysql=require('mysql')
//建立数据库连接
const db=mysql.createPool({
    
    
    host:'127.0.0.1',
    user:'root',
    password:'123456',
    database:'test2'
})
module.exports=db
  1. 建立路由
  • 公开路由,不用身份验证router/user.js
const express=require('express')
const router=express.Router()
//导入路由模块
const user_handler=require('../router-handler/user')
//导入验证数据中间件
const expressJoi=require('@escook/express-joi')
//导入验证规则对象
const {
    
    reg_sign_schema}=require('../schema/user')

//注册新用户
router.post('/reguser',expressJoi(reg_sign_schema),user_handler.reguser)
//登录
router.post('/sign',expressJoi(reg_sign_schema),user_handler.sign)
module.exports=router
  • 私有路由要验证router/userinfo.js
const express=require('express')
const router=express.Router()

//导入路由模块
const userinfo_handler=require('../router-handler/userinfo')

//导入数据验证中间件
const expressJoi=require('@escook/express-joi')
//导入验证条件
const {
    
    update_userinfo_schema,update_password_schema,update_avatar_schema,delete_user_shema}=require('../schema/user')
//获取用户基本信息
router.get('/userinfo',userinfo_handler.getUserinfo)

//更新用户信息
router.post('/updateUserinfo',expressJoi(update_userinfo_schema),userinfo_handler.updataUserinfo)

//重置密码
router.post('/updatePwd',expressJoi(update_password_schema),userinfo_handler.updatePassword)

//更换用户头像
router.post('/update/avatar',expressJoi(update_avatar_schema),userinfo_handler.updateAvatar)

//获取访客列表
router.get('/list',userinfo_handler.getList)

//删除用户
router.post('/delUser',expressJoi(delete_user_shema),userinfo_handler.getDelUser)
module.exports=router
  1. 路由执行代码
  • 公开路由执行代码router-handler/user.js
//导入数据库模块
const db=require('../db/index')
//加密模块
const bcrypt=require('bcryptjs')
//导入token模块
const jwt=require('jsonwebtoken')
const config=require('../schema/config')
const {
    
     TokenExpiredError } = require('jsonwebtoken')
//注册新用户
exports.reguser=(req,res)=>{
    
    
    const userinfo=req.body
    
    // if(!userinfo.name||!userinfo.password){
    
    
    //     // return res.send({
    
    
    //     //     status:1,
    //     //     message:'用户名或密码不为空'
    //     // })
    //     return res.cc('用户名或密码不为空')
    // }
  
    //定义数据库查询语句
    const sqlStr='SELECT * FROM ev_users WHERE username=?'
    db.query(sqlStr,[userinfo.username],function(err,results){
    
    
       
        if(err)return res.cc(err)
        if(results.length>0)return res.cc('用户名已占用')
        //加密
        userinfo.password=bcrypt.hashSync(userinfo.password,10)
    
        //注册新用户
        const newUserSql='insert into ev_users set ?'
        db.query(newUserSql,{
    
    username:userinfo.username,password:userinfo.password},(err,results)=>{
    
    
            if(err)return res.cc(err)
            if(results.affectedRows!==1)return res.cc('注册出错了')
            res.cc(err,0)
        })
        })
    
    }
//登录
exports.sign=(req,res)=>{
    
    
    const userinfo=req.body
    let usernanmSql='SELECT * FROM ev_users WHERE username=?'
    db.query(usernanmSql,userinfo.username,(err,results)=>{
    
    
        //判断用户
        if(err) return res.cc(err)
        if(results.length==0) return res.cc('用户名不存在')
        //判断密码
        const comparResults= bcrypt.compareSync(userinfo.password,results[0].password)
        if(!comparResults)return res.cc('密码错误')
        //生成token字符串
        const user={
    
    ...results[0],password:'',user_pic:''}
        //加密
        const tokenStr=jwt.sign(user,config.jwtSecretKey,{
    
    expiresIn:'10h'})
        res.send({
    
    
            status:0,
            message:'登录成功',
            token:'Bearer '+tokenStr
            
        })
    })
    
}
  • 私有路由执行代码router-handler/userinfo.js
//导入数据库模块
const db =require('../db/index')

//导入密码模块
const bcrypt=require('bcryptjs')

//查询用户信息函数
exports.getUserinfo=(req,res)=>{
    
    
    //定义字符串
    const sql='SELECT id,username,nickname,email,user_pic FROM ev_users WHERE id=?'
    //执行
    db.query(sql,req.user.id,(err,results)=>{
    
    
        if(err) return res.cc(err)
        if(results.length!==1) return res.cc('获取用户信息失败')
        res.send({
    
    
            status:0,
            message:'获取成功',
            data:results[0]
        })
    })
}

//更新用户数据
exports.updataUserinfo=(req,res)=>{
    
    
    //定义字符串
    const sql='UPDATE ev_users SET id=?,nickname=?,email=? WHERE id=?'
    //执行语句
    db.query(sql,[req.body.id,req.body.nickname,req.body.email,req.user.id],(err,results)=>{
    
    
        //执行成功但影响函数不为一
        if(err) return res.cc(err)
        console.log(results);
        if(results.affectedRows!==1) return res.cc('错误')
        return res.cc('修改成功',0)
    })
}

//重置密码
exports.updatePassword=(req,res)=>{
    
    
    const sql='SELECT * FROM ev_users WHERE id=?'
    //执行查询用户名是否存在操作
    db.query(sql,[req.user.id],(err,results)=>{
    
    
        if(err) return res.cc(err)
        if(results.length!==1) return res.cc('查询失败')
        //判定密码是否正确
        const comparePws= bcrypt.compareSync(req.body.oldPws,results[0].password)
        if(!comparePws) return res.cc('密码出错')
        //执行重置密码
        const sql='UPDATE ev_users SET password=? WHERE id=?'
        const newPws=bcrypt.hashSync(req.body.newPws,10)
        db.query(sql,[newPws,req.user.id],(err,results)=>{
    
    
            if(err) return res.cc(err)
            if(results.affectedRows!==1) return res.cc('更改密码出错')
            res.cc('成功',0)
        })
    })
}

//更换用户头像
exports.updateAvatar=(req,res)=>{
    
    
    const sql='UPDATE ev_users SET user_pic=? WHERE id=?'
    db.query(sql,[req.body.avatar,req.user.id],(err,results)=>{
    
    
        if(err) return res.cc(err)
        if(results.affectedRows!==1) return res.cc('更改失败')
        res.cc('更换成功',0)
    })
}

//获取所有用户信息列表
exports.getList=(req,res)=>{
    
    
    const sql='SELECT * FROM ev_users'
    db.query(sql,(err,results)=>{
    
    
        if(err) return res.cc(err)
        res.send({
    
    
            status:0,
            message:'获取成功',
            data:results
        })
    })
}

//删除用户
exports.getDelUser=(req,res)=>{
    
    
    
    const sql='DELETE FROM ev_users WHERE id=?'
    db.query(sql,[req.body.id],(err,results)=>{
    
    
        console.log(req.body.id);
        if(err) return res.cc(err)
        if(results.affectedRows!==1) return res.cc('删除错误')
        res.cc('删除成功',0)
    })
}
  1. 模式验证与密钥
  • 模式验证schema/user,js
const joi=require('joi')
//string()字符串
//alphanum()值只能是0-9a-zA-Z
//min()最小长度
//max()最大长度
//required()必填项
//pattren(正则表达式)

//用户名验证规则
const username=joi.string().min(4).max(10).required()
//密码验证规则
const password=joi.string().required()
//更换头像验证规则
const avatar=joi.string().required()
//注册和登录验证对象
exports.reg_sign_schema={
    
    
    body:{
    
    
        username,
        password
    },
}

//定义id,nickname,email验证规则
const id=joi.number().integer().min(1).required()
const nickname=joi.string().required()
const email=joi.string().email().required()
//更新用户名验证对象
exports.update_userinfo_schema={
    
    
    body:{
    
    
        id,
        nickname,
        email
    }
}

//更新密码验证
exports.update_password_schema={
    
    
    body:{
    
    
        oldPws:password,
        //ref继承,not不等于,concat合并两个条件
        newPws:joi.not(joi.ref('oldPws')).concat(password)
    }
}

//更换头像规则验证
exports.update_avatar_schema={
    
    
    body:{
    
    
        avatar
    }
}

//删除id验证
exports.delete_user_shema={
    
    
    body:{
    
    
        id
    }
}
  • 密钥schema/config.js
//全局配置文件
module.exports={
    
    
    //密钥
   jwtSecretKey: 'this is key',
     
      
}
  1. 因为是在区域网内进行的测试还需要个代码web.js托管前端代码
const express=require('express')
const app=express()
app.use(express.static('web'))

app.listen(3000,function(){
    
    
console.log('express server tunning');
})

//浏览器输入http://localhost/index.html拿到html中内容
  1. app.js
//导入express模块
const express=require('express')
const app=express()
const joi=require('joi')
//解决跨域问题
const cors=require('cors')
app.use(cors())
//解析表单数据
app.use(express.urlencoded({
    
    extended:false}))
//封装res.send()响应错误信息
app.use(function(req,res,next){
    
    
    //status值默认失败1
    res.cc=function(err,status=1){
    
    
        res.send({
    
    
            status,
            message:err instanceof Error ?err.message:err,
        })
    }
    next()
})
//导入密钥
const config=require('./schema/config')
//导入解析token模块
const expressJWT=require('express-jwt')
//指定哪些接口不需要认证
app.use(expressJWT({
    
    secret:config.jwtSecretKey,algorithms: ['HS256']}).unless({
    
    path:[/^\/api/]}))
//导入用户路由模块
const userRouter=require('./router/user')
app.use('/api',userRouter)

//导入用户信息路由模块
const userinfoRouter=require('./router/userinfo')
app.use('/my',userinfoRouter)
//定义错误级别中间件
app.use((err,req,res,next)=>{
    
    
    //验证失败错误
    if(err instanceof joi.ValidationError) return res.cc(err)
    //身份认证出错
    if(err.name==='UnauthorizedError') return res.cc('身份认证出错')
    res.cc(err)
})


//启动监听端口
app.listen(4000,function(){
    
    
    console.log('express listen running at 4000');
})

猜你喜欢

转载自blog.csdn.net/weixin_64925940/article/details/124314678