server.js
const fs = require("fs")
const urlLib = require('url')
const http = require('http')
const querystring = require('querystring')
var users={}
http.createServer(function(req,res){
var obj = urlLib.parse(req.url,true)
var url = obj.pathname
// get
var GET = obj.query
// post
var str =''
req.on('data',function(data){
str+=data
})
req.on('end',function(){
const POST = str
})
/*区分接口、文件 */
if(url=='/user'){ //接口
switch(GET.act){
case 'reg':
// 1.检查用户名是否已经有了
if(users[GET.user]){
res.write('{"ok":false,"msg":"此用户已存在"}')
}else{//2.插入users
users[GET.user]=GET.pass
res.write('{"ok":true,"msg":"注册成功"}')
}
break;
case 'login':
// 1.检查用户是否存在
if(users[GET.user]==null){
res.write('{"ok":false,"msg":"此用户不存在"}')
}else if(users[GET.user]!=GET.pass){ //2.检查用户密码
res.write('{"ok":false,"msg":"用户名或密码错误"}')
}else{
res.write('{"ok":true,"msg":"登录成功"}')
}
break;
default:
res.write('{"ok":false,"msg":"未知的act"}')
}
res.end()
}else{ //文件
var file_name = './www'+url
fs.readFile(file_name,function(err,data){
if(err){
res.write('404')
}else{
res.write(data)
}
res.end()
})
}
}).listen(8080)
user.html
<!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">
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<title>Document</title>
</head>
<body>
用户:<input type="text" id="user"><br>
密码:<input type="possword" id="pass"><br>
<input type="button" value="注册" id="reg_btn">
<input type="button" value="登录" id="login_btn">
<script>
var TextUser = document.getElementById('user')
var TextPass = document.getElementById('pass')
var BtnReg = document.getElementById('reg_btn')
var BtnLogin = document.getElementById('login_btn')
BtnReg.onclick=function(){
$.ajax({
type:'get',
url: "/user",
data: {
act:'reg',
user:TextUser.value,
pass:TextPass.value
},
success: function (str) {
var json = eval('('+str+')')
if(json.ok){
alert('注册成功')
}else{
alert('注册失败:'+json.msg)
}
},
error:function(){
alert("通信错误")
}
});
}
BtnLogin.onclick=function(){
$.ajax({
type:'get',
url: "/user",
data: {
act:'login',
user:TextUser.value,
pass:TextPass.value
},
success: function (str) {
var json = eval('('+str+')')
if(json.ok){
alert('登录成功')
}else{
alert('登录失败:'+json.msg)
}
},
error:function(){
alert("通信错误")
}
});
}
</script>
</body>
</html>
运行server.js,打开localhost:8080/user.html,就可以测试啦