筆記
首先定義接口
接口名稱: /user
請求參數:act=reg&username=aaa&pass=123456
act的值區分是註冊還是登錄
username是用戶名
pass是密碼
返回值 {'ok':false,'msg':'原因'}
需求是這樣的
先說註冊
1.輸入用戶名跟密碼提交註冊時後臺判斷該用戶名是否已經存在,如果已經存在就提示用戶該用戶名已經存在,否則註冊成功
登錄
1.輸入用戶名跟密碼提交登錄時判斷該用戶名是否已經註冊,沒有註冊提示用戶先去註冊,如果已經註冊判斷輸入的密碼是否與註冊時的密碼一致,不一致時提醒用戶名賬號或者密碼輸入錯誤,一致時直接是登錄成功
html代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>POST發送表單</title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
</head>
<body>
<p>註冊</p>
<form name='regiForm'>
用戶名:
<input type="text" name="name" id="">
密碼:
<input type="password" name="pass" id="">
</form>
<button class="registered">註冊</button>
<p>登錄</p>
<form name='loginForm'>
用戶名:
<input type="text" name="name" id="">
密碼:
<input type="password" name="pass" id="">
</form>
<button class="login">登錄</button>
</body>
<script>
$(function () {
$('.registered').click(function () {
$.ajax({
// async: false,
type: 'GET',
url: 'http://localhost:8888/user',
data: {
act: 'reg',
name:regiForm.name.value,
pass:regiForm.pass.value
},
success: function (res) {
let result=JSON.parse(res)
if(result.ok){
console.log('註冊成功')
}else{
console.log(result.msg)
}
},
error: function () {
console.log('網絡錯誤')
}
});
})
$('.login').click(function () {
$.ajax({
// async: false,
type: 'GET',
url: 'http://localhost:8888/user',
data: {
act: 'login',
name:loginForm.name.value,
pass:loginForm.pass.value
},
success: function (res) {
let result=JSON.parse(res)
if(result.ok){
console.log('登錄成功')
}else{
console.log(result.msg)
}
},
error: function () {
console.log('網絡錯誤')
}
});
})
})
</script>
</html>
server.js代碼
const http = require("http");
const fs = require("fs");
const querystring = require("querystring");
const URL = require("url");
var users = {};
http
.createServer(function(req, res) {
var postStr = "";
req.on("data", function(data) {
postStr += data;
});
req.on("end", function() {
var obj = URL.parse(req.url, true);
console.log(obj)
const url = obj.pathname;
const get = obj.query;
const post = querystring.parse(postStr);
console.log(url)
// 判斷是否是接口
if (url == "/user") {
//註冊
if (get.act =="reg") {
if (users[get.name]) {
res.write('{"ok":false,"msg":"該用戶已經存在,可以直接登錄"}');
} else {
users[get.name] = get.pass;
res.write('{"ok":true,"msg":"註冊成功"}');
}
//登錄
} else if (get.act == "login") {
if (!users[get.name]) {
res.write('{"ok":false,"msg":"該用戶還沒註冊"}');
} else if (users[get.name] != get.pass) {
res.write('{"ok":false,"msg":"密碼錯誤"}');
} else {
res.write('{"ok":true,"msg":"登錄成功"}');
}
} else {
res.write('{"ok":false,"msg":"沒有該類型的文件"}');
}
res.end();
} else {
var file_name = './' + req.url;
fs.readFile(file_name, function (err, data) {
if (err) {
res.write('404');
} else {
res.write(data.toString());
}
res.end();
})
}
});
// res.end();
})
.listen(8888);