前端学习(554):node实现登录和注册第二部分代码
生活随笔
收集整理的這篇文章主要介紹了
前端学习(554):node实现登录和注册第二部分代码
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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
再點擊注冊
點擊登錄
總結
以上是生活随笔為你收集整理的前端学习(554):node实现登录和注册第二部分代码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 三级数据库考mysql_计算机三级MyS
- 下一篇: 前端学习(1390):多人管理项目10服