共计 2137 个字符,预计需要花费 6 分钟才能阅读完成。
思路:
- 登录因为传的数据不是特地多,所以用 get 形式申请;
- 注册因为传的数据波及到头像文件上传都得用 post 形式申请。
一、创立登录界面 login.html,ajax 申请接口采纳 jQuery。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> 登录 </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>
<button id="reg"> 注册 </button>
<script>
$('#login').click(function () {
$.ajax({
url: "/login",
data: {username: $("#username").val(),
password: $("#password").val()},
dataType: "json",
success(res) {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) {if (res.err) {alert(res.msg)
} else {alert("注册胜利")
}
}
})
})
</script>
</body>
</html>
二、服务端 nodejs 接口 API 解决逻辑:
- 判断申请形式,获取申请过去的数据;
- 通过门路判断申请的接口是 login 还是 reg;
- 校验用户名明码的正确性及是否存在;
- 输入状态码及信息给前端判断是否胜利。
let http = require('http');
let url = require('url');
let querystring = require('querystring');
let fs = require('fs');
// 这边采纳动态数组
let user = {admin: 123456}
http.createServer((req, res) => {
let path, getData, postData
if (req.method == 'GET') {let { pathname, query} = url.parse(req.url, true);
path = pathname;
getData = query;
complete();} else if (req.method == 'POST') {let result = [];
path = req.url;
req.on('data', buffer => {result.push(buffer)
});
req.on("end", () => {postData = querystring.parse(Buffer.concat(result).toString());
complete();})
}
function complete() {if (path == '/login') {
res.writeHead(200, {'Content-Type': 'text/plain;charset=utf-8'})
let {username, password} = getData;
if (!user[username]) {
res.end(JSON.stringify({
err: 1,
msg: '用户名不存在'
}))
} else if (user[username] != password) {
res.writeHead(200, {'Content-Type': 'text/plain;charset=utf-8'})
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} = postData;
if (user[username]) {
res.end(JSON.stringify({
err: 1,
msg: '用户曾经存在'
}))
} else {user[username] = password;
res.end(JSON.stringify({
err: 0,
msg: '注册胜利'
}))
}
} else {fs.readFile(`./${path}`, (err, data) => {if (err) {res.end('404');
} else {res.end(data);
}
})
}
}
}).listen(8088)
正文完