Node小实验--用户注册登录
用户登录的表单
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="./jquery.js"></script> </head> <body> <input type="text" id="uname"><br> <input type="password" id="pwd"><br> <input type="button" id="reg" value="注册"> <input type="button" id="login" value="登录"> <input type="button" id="index" value="首页"> </body> <script> $("#reg").on("click",function(){ $.get( "http://localhost:8080/user?act=reg", {"uname":$("#uname").val(),"pwd":$("#pwd").val()}, function(data){ data = JSON.parse(data); if(data['ok']==1){ alert("注册成功"); } else { alert("注册失败" + data['msg']); } } ); }); $("#login").on("click",function(){ $.get( "http://localhost:8080/user?act=login", {"uname":$("#uname").val(),"pwd":$("#pwd").val()}, function(data){ data = JSON.parse(data); if(data['ok']==1){ alert("登录成功"); } else { alert("登录失败" + data['msg']); } } ); }); $("#index").on("click",function(){ $.get( "http://localhost:8080/index.html", {}, function(data){ document.write(data); } ); }); </script> </html>
Node后端
const http = require("http"); const fs = require("fs"); const urlLib = require("url"); const querystring = require("querystring"); var users = {}; var server = http.createServer(function(request,response){ //接收get请求 var obj = urlLib.parse(request.url,true); var url = obj.pathname; const GET = obj.query; //接收post请求 var tmp = ""; //使用字符串来保存不是最好的方式,提示:接收文件 request.on("data",function(data){ tmp += data; }); request.on("end",function(){ const POST = querystring.parse(tmp); if(url == "/user"){ switch(GET["act"]){ case "reg": if(users[GET["uname"]]){ response.write('{"ok":0,"msg":"该用户已注册"}'); } else { users[GET['uname']]=GET['pwd']; response.write('{"ok":1,"msg":"注册成功"}'); } break; case "login": if(GET['pwd'] && users[GET['uname']] && GET['pwd']==users[GET['uname']]){ response.write('{"ok":1,"msg":"欢迎"}'); } else { response.write('{"ok":0,"msg":"用户名或密码错误"}'); } break; default: response.write("404"); } response.end(); } else { //文件读 fs.readFile("./www/"+ url,function(err,data){ if(err){ response.write("404"); } else { response.write(data); } response.end(); }); } //服务器端打印相关参数 console.log(" 请求资源:",url); console.log(" GET请求参数:",GET); console.log(" POST请求参数:",POST); console.log(" 当前用户:",users); }); }); server.listen(8080);
如需转载,请注明文章出处,谢谢!!!