參考html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="jQuery.js"></script> <script> window.onload = function () { var oTxtUser = document.getElementById('user'); var oTxtPass = document.getElementById('pass'); var oBtnReg = document.getElementById('reg_btn'); var oBtnLogin = document.getElementById('login_btn'); oBtnLogin.onclick = function(){ $.ajax({ url:'/user', data:{act:'login',user:oTxtUser.value,pass:oTxtPass.value}, type:'get', success:function (str) { var json = eval('('+str+')'); if(json.ok){ alert("登錄成功") }else { alert("登錄失敗" + json.msg) } }, error:function () { alert('通訊錯誤') } }) } oBtnReg.onclick = function () { $.ajax({ url:'/user', data:{act:'reg',user:oTxtUser.value,pass:oTxtPass.value}, type:'get', success:function (str) { var json = eval('('+str+')'); if(json.ok){ alert("註冊成功") }else { alert("註冊失敗" + json.msg) } }, error:function () { alert('通訊錯誤') } }) } } </script> </head> <body> 用戶名:<input type="text" id="user"><br> 密碼:<input type="password" id="pass"><br> <input type="button" id="reg_btn" value="註冊"> <input type="button" id="login_btn" value="登錄"> </body> </html>
const http = require('http'); const fs = require('fs'); const querystring = require('querystring'); const urlLib = require('url'); var users = {};//模擬 http.createServer(function (req,res) { //解析數據 var str = ''; //模擬 req.on("data",function (data) { str += data; }); req.on("end",function (err) { var obj = urlLib.parse(req.url,true); const url = obj.pathname; const GET = obj.query; const POST = querystring.parse(str); //區分 接口 文件 if(url == '/user'){//接口 switch (GET.act){ case 'reg': //1.檢查用戶名是否已經有了 if(users[GET.user]){ res.write('{"ok":false,"mag":"此用戶已存在"}'); }else { //2.插入users users[GET.user] = GET.pass; res.write('{"ok":true,"mag":"註冊成功"}'); } break; case 'login': if(users[GET.user] == null){//1.檢查用戶是否存在 res.write('{"ok":false,"mag":"此用戶不存在"}'); }else if(users[GET.user] != GET.pass){//2.檢查用戶密碼是否正確 res.write('{"ok":false,"mag":"用戶名或密碼有誤"}'); }else { res.write('{"ok":true,"mag":"登錄成功"}'); } break; default: res.write('{"ok":false,"mag":"未知的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);