node.js(四)小结
生活随笔
收集整理的這篇文章主要介紹了
node.js(四)小结
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
用之前的內容寫一個簡單的注冊登錄
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.pathnameconst GET = obj.queryconst 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.passres.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、檢查用戶密碼breakdefault:res.write("{'ok':false,'msg':'未知的act'}")}res.end();} else { // 文件// 讀取文件var file_name = './www/' + urlfs.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
轉載于:https://www.cnblogs.com/YAN-HUA/p/10893438.html
總結
以上是生活随笔為你收集整理的node.js(四)小结的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: maven项目添加文件夹报错
- 下一篇: laravel homestead环境默