1.在app.js中托管静态资源,挂路由
托管:app.use(express.static('myPro'));
路由:
var myPro=require('./routes/myPro.js');
app.use('/myPro',myPro);
2.ajax登录功能(post)
在myPro文件夹中创建一个common.js,在common.js中编写$()和createXhr()函数。
var router=express.Router();
router.post('/ajaxlogin',(req,res)=>{
var $uname=req.body.uname;
if(!$uname){
res.send('用户名称不存在');
return;
}
var $upwd=req.body.upwd;
if(!$upwd){
res.send('用户密码不存在');
return;
}
var sql='select * from xz_user where uname=? and upwd=?';
pool.query(sql,[$uname,$upwd],(err,result)=>{
if(result.length>0){
res.send("登录成功!");
}else{
res.send("用户或密码错误!");
}
});
});
module.exports=router;
<!doctype html>
<html>
<head>
<title>ajaxlogin</title>
<meta charset="utf-8">
<style></style>
</head>
<body>
<p>
用户名称:<input type="text" id="uname">
</p>
<p>
用户密码:<input type="password" id="upwd">
</p>
<p>
<input type="button" value="登录" οnclick="ajaxlogin()">
</p>
<script src="common.js"></script>
<script>
function ajaxlogin(){
//1.创建异步对象
var xhr=createXhr();
//2.监听
xhr.onreadystatechange=function(){
if(xhr.readyState==4&&xhr.status==200){
var res=xhr.responseText;
console.log(res);
alert(res);
}
}
//3.打开连接
xhr.open("post","/myPro/ajaxlogin",true);
//增加:消息头
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//4.发送请求
var uname=$("uname").value;
var upwd=$("upwd").value;
var url="uname="+uname+"&upwd="+upwd;
xhr.send(url);
}
</script>
</body>
</html>