登录页面图:
node.js文件代码:
const express=require("express"); const app=express(); const path=require("path") const cors=require("cors") const bodyParser=require("body-parser") const db=require("./util/configDb.js") app.listen(3000,()=>{ console.log("app start........") }) app.use(bodyParser.urlencoded({ extended:true })) app.use(bodyParser.json()) app.use(cors()) app.use("/static",express.static(path.join(__dirname,"./views"))) app.post("/login",(req,res)=>{ console.log("服务端",req.body) const {name,pwd}=req.body; let sql=`select * from user where name=${name} and pwd=${pwd}` console.log("sql",sql) let sqlObj=[] console.log("sqlObj",sqlObj) let callBack=function(err,data){ console.log("data:",data.length) if(err){ console.log("失败") return } if(data.length!=1){ console.log("密码或用户名出错") res.send({ msg:"用户名或密码出错", code:400 }) return } res.send({ msg:"成功登录", code:200 }) } db.dbConn(sql,sqlObj,callBack) })
configDb.js文件代码
const mysql=require("mysql") module.exports={ config:{ host:"localhost", user:"root", password:"", database:"infodb" }, dbConn:function(sql,sqlObj,callBack){ let pool=mysql.createPool(this.config) pool.getConnection((err,conn)=>{ if(err){ console.log(err) return; } conn.query(sql,sqlObj,callBack) conn.release(); }) } }
index.html文件代码:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /> <title>登录</title> <style type="text/css"> *{ margin: 0px; padding: 0px; } body{ width: 100%; height: 100%; background-color: #f5f5f5; } .area-box{ display: flex; flex-direction: column; justify-content: center; align-items: center; margin-top: 100px; } .login-group{ /* width: 100%; */ height: 40px; background-color: white; padding: 10px 30px; } .login-group input{ height: 24px; outline: none; border-radius: 20px; padding-left: 10px; } .login-btn{ margin-top: 20px; } .login-btn button{ width: 200px; height: 30px; line-height: 30px; border-radius: 20px; outline: none; } </style> </head> <body> <div class="area-box"> <div class="login-group"> <label>用户:</label> <input type="text" name="" id="phone" placeholder="请输入手机号" /> </div> <div class="login-group"> <label>密码:</label> <input type="password" name="" id="pwd" placeholder="请输入密码" /> </div> <div class="login-btn"> <button type="button" id="login">登录</button> </div> </div> <script src="js/jquery-3.3.1.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> let phone=$("#phone") let pwd=$("#pwd") $("#login").click(function(){ if(phone.val().length==0||pwd.val().length==0){ alert("用户或密码不能为空") return; } var getPhone=phone.val() var getPwd=pwd.val() var data={ "name":getPhone, "pwd":getPwd } $.ajax({ type:"POST", url:"http://localhost:3000/login", data:data, success:res=>{ console.log(res) if(res.code==200){ alert(res.msg) }else{ alert(res.msg) } }, error:err=>{ console.log(err) } }) }) </script> </body> </html>