前端代码
<!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>
<link href="./node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
.container-small{
max-width: 500px;
}
.btns .btn1{
float:left ;
}
.btns .btn2{
float:right ;
}
.alert{
display: none;
}
</style>
</head>
<body>
<div class="alert alert-danger container container-small" >发布错误</div>
<div class="container container-small">
<h1>登录</h1>
<div>
<div class="form-group">
<label for="">用户名</label>
<input type="text" class="form-control user" name="username">
</div>
<div class="form-group">
<label for="">密码</label>
<input type="text" class="form-control psw" name="password">
</div>
</div>
<div class="btns">
<button class="btn btn-primary btn1">登录</button>
<button class="btn btn-primary btn2">注册</button>
</div>
</div>
<script src="./node_modules/jquery/dist/jquery.min.js"></script>
<script src="./node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<script>
$(function(){
var method;
var $user=$('.user'),$psw=$('.psw'),$alert=$('.alert');
$("body").on('click','.btn1,.btn2',function(ev){
ev=ev||event;
(ev.target.className.includes('btn1'))?method='get':method='post'
$.ajax({
url:'/submit',
type:method,
data:{
username:$user.val(),
password:$psw.val()
},
success:function(data){
$user.val('');
$psw.val('');
$alert.text(data).slideDown(1000,function(){
$alert.slideUp(1000)
})
},
error:function(err){
console.log(err)
}
})
})
})
</script>
</body>
</html>
后端代码
const express=require('express');
const app=express();
const bodyParser=require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false })
let username,password;
app.get('/submit',(req,res)=>{
console.log(username,password)
if(req.query.username==username){
if(req.query.password==password){
res.send("登录成功")
}else{
res.send("密码错误")
}
}else{
res.send("用户名错误")
}
})
// POST /login gets urlencoded bodies
app.post('/submit', urlencodedParser, function (req, res) {
username=req.body.username;
password=req.body.password;
res.send("注册成功")
})
app.use('/',express.static('../login'))
app.listen('8989');
运行效果