registration.html -- 注冊頁面
<body>
<h1>注冊</h1>
用戶名:<input id="user" type="text" placeholder="請輸入您的用戶名"/><br/>
密 碼:<input id="pass" type="password" placeholder="請輸入您的密碼"/><br/>
<button id="reg">注冊</button>
</body>
<script>
reg.onclick=function(){
ajax({
type:"get",
url:"http://127.0.0.1:7766/reg",
data:{
username:user.value,
password:pass.value
},
success:function(res){
if(res=="注冊成功"){
alert(res);
// 設(shè)置延時器 跳轉(zhuǎn)到登錄頁面
setTimeout(function(){
window.location.href="./login.html"
},1000);
}else{
alert(res);
}
}
})
}
</script>
login.html -- 登錄頁面
<body>
<h1>登錄</h1>
用戶名:<input id="user" type="text" placeholder="請輸入您的用戶名"/><br/>
密 碼:<input id="pass" type="password" placeholder="請輸入您的密碼"/><br/>
<button id="login">登錄</button>
</body>
<script>
login.onclick=function(){
ajax({
type:"get",
url:"http://127.0.0.1:7766/login",
data:{
username:user.value,
password:pass.value
},
success:function(res){
if(res=="登陸成功"){
alert("登陸成功")
}else{
alert("登陸失敗")
}
}
})
}
</script>
注冊和登錄頁面里的ajax用的是我自己封裝的一個原生ajax 稍后會發(fā)布一個我自己封裝的原生ajax
server.js -- 服務(wù)器
var http = require("http");
// var jsonData = require("./data.json")
var url = require("url");
var qs = require("querystring")
var user = [
// 對象屬性名最好和前面html的對應(yīng)
{
username:"song",
password:"1500111"
},
{
username:"sun",
password:"1343957"
}
]
http.createServer(function(req,res){
// 跨域
res.setHeader("Access-Control-Allow-Origin","*");
res.writeHead(200,{"Content-type":"text/html;charset=utf-8"});
// 控制臺不會報小圖標(biāo)的錯
if(req.url == "favicon.ico"){
res.end(null);
return;
}
var query = url.parse(req.url,true).query;
// console.log(req.url)
// 判斷頁面是登陸還是注冊
//console.log(url.parse(req.url).pathname)// /reg || /login
if(url.parse(req.url).pathname=="/reg"){
// get提交
var username = query.username;
// 遍歷用戶數(shù)據(jù)數(shù)組 -- some 方法 只要有一個符合條件就返回true
var reg_result = user.some( i=> i.username == username );
if(reg_result){
res.end("已經(jīng)注冊過了");
}else{
res.end("注冊成功");
user.push(query);
// console.log(user)
}
}else if(url.parse(req.url).pathname=="/login"){
var login_result = user.some( i=> JSON.stringify(i) == JSON.stringify(query) );
console.log( user[0]);
console.log(typeof query)
if(login_result){
res.end("登陸成功")
}else{
res.end("登錄失敗")
}
}
}).listen(7766,function(){
console.log("ok 7766")
})
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。