用之前的内容写一个简单的注册登录
const http = require('http') const urlLib = require('url') const fs = require('fs') const querystring = require('querystring') var users = {} // {"name":"password"} 模拟数据库存储数据 var server = http.createServer(function (req, res) { // 解析数据 var str = '' req.on('data', function (data) { str += str }) req.on('end', function () { var obj = urlLib.parse(str, true); const url = obj.pathname const GET = obj.query const POST = querystring.parse(str) if (url == '/user') { //console.log(GET) switch (GET.act) { case 'reg': //1、用戶是否存在 if (users[GET.user]) { res.write('{"ok":false,"msg":"用戶已存在"}') } else { //2、插入 users[GET.user] = GET.pass res.write('{"ok":true,"msg":"註冊成功"}') } break; case 'login': //1、用戶是否存在 if (users[GET.user] == null) { res.write('{"ok":false,"msg":"用戶不存在"}') res.end(); } else if (users[GET.user] != GET.pass) { res.write('{"ok":false,"msg":"用戶名或密碼有誤"}') res.end(); } else { res.write("{'ok':true,'msg':'登錄成功'}"); } //2、檢查用戶密碼 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() }) } }) }); server.listen(8080)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> 用戶名:<input type="text" name="user" id="user"><br> 密碼:<input type="password" name="pass" id="pass"><br> <input type="button" value="註冊" id="reg_btn"> <input type="button" value="登錄" id="login_btn"> <script> window.onload = function () { var oTxtUser = document.getElementById('user'); var oTxtPass = document.getElementById('pass'); var oBtnReg = document.getElementById('reg_btn'); var oBtnLongin = document.getElementById('login_btn'); function ajaxFun(act) { var xhr = new XMLHttpRequest(); xhr.open('GET', '/user?user=' + oTxtUser.value + '&pass=' + oTxtPass.value + '&act=' + act, true); xhr.send(); xhr.onreadystatechange = function () { // readyState == 4说明请求已完成 if (xhr.readyState == 4 && xhr.status == 200 || xhr.status == 304) { // 从服务器获得数据 console.log(xhr.responseText) } }; } oBtnReg.onclick = function () { ajaxFun("reg") } oBtnLongin.onclick = function () { ajaxFun("login") } } </script> </body> </html>
运行代码 node xxx.js
在浏览器输入http://localhost:8080/user.html