1. html 页面(fetch请求)
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<label>请输入用户名:</label><input type="text"><br>
<label>请输入密码:</label><input type="text"><br>
<button onclick="show()" >登录</button>
<script>
let input=document.querySelectorAll("input");
function show(){
let username=input[0].value;
let pwd=input[1].value;
let url="http://localhost:9005";
let person=`username=${username}&pwd=${pwd}`;
url=url+"/?"+person;
fetch(url,{
method:"get"
// method:"post",
// body:person
}).then(function(res){
return res.text();
}).then(function(data){
console.log(data);
})
}
</script>
</body>
</html>
2. js 模块
注:需要先在命令行里下载mysql包。
cnpm install mysql
代码:
let http=require("http");
let mysql=require("mysql");
let PORT="9005";
let result={};
http.createServer(function(req,res){
res.setHeader("Access-Control-Allow-Origin","*");
if(req.method=="get"||req.method=="GET"){
let url=decodeURI(req.url);
let aaa=url.split("?")[1];
let arr=aaa.split("&");
let username,pwd;
arr.forEach(function(item){
let con=item.split("=");
if(con[0]=="username"){
username=con[1];
}else if(con[0]=="pwd"){
pwd=con[1];
}
})
show(username,pwd,function(data){
res.write(JSON.stringify(data));
res.end()
})
}else if(req.method=="post"||req.method=="POST"){
let data="";//保存数据
req.on("data",function(chunk){
data+=chunk;
});
req.on("end",function(){
let arr=data.split("&");
let username,pwd;
arr.forEach(function(item){
let con=item.split("=");
if(con[0]=="username"){
username=con[1];
}else if(con[0]=="pwd"){
pwd=con[1];
}
})
show(username,pwd,function(data){
res.write(JSON.stringify(data));
res.end()
})
})
}
}).listen(PORT)
console.log("服务器开启成功。。。。。。。")
function show(username,pwd,fn){
let conn=mysql.createConnection({
host:"localhost",
user:"root",
password:"liushiqi",
database:"mytest2"
})
conn.connect();
let sql=`SELECT * FROM mytest2.user where username='${username}' and pwd=${pwd};`
conn.query(sql,function(err,data){
if(!err){
if(data.length>0){
result.code="200";result.msg="登录成功"
fn(result);
}else{
result.code="202";result.msg="登录失败"
fn(result)
}
}else{
result.code="402";result.msg="数据库走丢了"
fn(result)
}
})
}