jquery.min.js
npm安装jQuery并引入
app.js
const http = require('http');
const url = require('url')
const querystring = require('querystring')
const fs = require('fs')
let user={admin:12345
}
http.createServer((req,res)=>{let path,get,post//如果是get请求if(req.method=='GET'){let{pathname,query} = url.parse(req.url,true)path=pathname,get=querycomplete()//如果是POST请求}else if(req.method=='POST'){let arr=[]path=req.urlreq.on('data',buffer=>{arr.push(buffer)})req.on('end',()=>{post=querystring.parse(Buffer.concat(arr).toString())complete()})}function complete(){if(path=='/login'){res.writeHead(200,{"Content-Type":"text/plain;charset=utf-8"})let {username,password}=getif(!user[username]){res.end(JSON.stringify({err:1,msg:"用户不存在"}))}else if(user[username]!=password){res.end(JSON.stringify({err:1,msg:"密码错误"}))}else{res.end(JSON.stringify({err:0,msg:"登录成功"}))}}else if(path=='/reg'){res.writeHead(200,{"Content-Type":"text/plain;charset=utf-8"})let{username,password}=postif(user[username]){res.end(JSON.stringify({err:1,msg:"账户已经存在"}))}else{user[username]=passwordres.end(JSON.stringify({err:0,msg:"注册成功"}))}}else{fs.readFile(`./${path}`,(err,data)=>{if(err){res.end('404')}else{res.end(data)}})}}
}).listen(8887);
login.html
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><script src="jquery.min.js"></script>
</head>
<body>用户名:<input type="text" id="username"><br/> 密码:<input type="password" id='password'><br/><button id="login">登录</button><br/><button id="reg">注册</button><br/><script>$('#login').click(function() {$.ajax({url: "/login",data: {username: $('#username').val(),password: $('#password').val()},dataType: "json",success(res) {//执行成功返回的是json值if (res.err) {alert(res.msg)} else {alert("登录成功")location.href="admin.html"}}})})$('#reg').click(function() {$.ajax({url: "/reg",method:"post",data: {username: $('#username').val(),password: $('#password').val()},dataType: "json",success(res) {//执行成功返回的是json值if (res.err) {alert(res.msg)} else {alert("注册成功")}}})})</script>
</body>
</html>
admin.html
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<body><p>我是歌谣(后台)</p>
</body>
</html>
开启服务器
运行结果
输入网址
h
admin 123
admin 12345
点击注册
mdsdr 123
再点击注册
点击登录