server.js
//引入node的http模块
const http = require('http');
//引入node的url模块
const url = require('url')
//引入node的querystring模块
const querystring = require('querystring');
//引入node的file system模块
const fs = require('fs');
let users = {}
//创建一个HTTP服务器
let server = http.createServer((req,res)=>{
//get
let {pathname,query} = url.parse(req.url,true);
//post
let str = '';
//post数据要分段接收,因为浏览器会分段发送
//有一段数据到达
req.on('data',data=>{
str += data
})
//所有数据都到达完毕
req.on('end',()=>{
let post = querystring.parse(str)
//写东西
switch(pathname){
case '/reg'://注册
{
let {user,password} = query;
//可以返回中文响应
res.writeHead(200,{ 'Content-Type': 'text/plain;charset=utf-8'});
if(!user){
res.write('{"err":1,"msg":"用户名必须"}')
}else if(!password){
res.write('{"err":1,"msg":"密码必须"}')
}else if(!/^\w{8,32}$/.test(user)){
res.write('{"err":1,"msg":"用户名不合法"}')
}else if(/^['|"]$/.test(password)){
res.write('{"err":1,"msg":"密码不合法"}')
}else if(users[user]){
res.write('{"err":1,"msg":"用户名已存在"}')
}else{
users[user] = password
res.write('{"err":0,"msg":"注册成功"}')
}
res.end()
break;
}
case '/login':
{
let {user,password} = query;
//可以返回中文响应
res.writeHead(200,{ 'Content-Type': 'text/plain;charset=utf-8'});
if(!user){
res.write('{"err":1,"msg":"用户名必须"}')
}else if(!password){
res.write('{"err":1,"msg":"密码必须"}')
}else if(!/^\w{8,32}$/.test(user)){
res.write('{"err":1,"msg":"用户名不合法"}')
}else if(/^['|"]$/.test(password)){
res.write('{"err":1,"msg":"密码不合法"}')
}else if(!users[user]){
res.write('{"err":1,"msg":"用户名不存在"}')
}else if(users[user] != password){
res.write('{"err":1,"msg":"用户名或密码错误"}')
}else{
res.write('{"err":0,"msg":"登录成功"}')
}
res.end()
break;
}
default:
fs.readFile(`www${pathname}`,(err,data)=>{
if(err){
res.writeHead(404)
res.write('Not Found')
}else{
res.write(data)
}
res.end()
})
}
})
});
//指定端口5000
server.listen(5000)
1.html
<html>
<head>
<meta charset="utf-8">
<title>标题</title>
<script src="jquery.js"></script>
<script>
$(function(){
$('#btn1').click(function(){
console.log(22);
$.ajax({
url:'/login',
data:{
user:$('#user').val(),
password:$('#password').val(),
},
dataType:'json',
success(data){
console.log(data);
},
error(err){
console.log(err);
}
})
});
$('#btn2').click(function(){
$.ajax({
url:'/reg',
data:{
user:$('#user').val(),
password:$('#password').val(),
},
dataType:'json',
success(data){
console.log(data);
},
error(err){
console.log(err);
}
})
})
})
</script>
</head>
<body>
<h1>读取文件操作后的内容</h1>
用户名:<input type="text" id="user"><br>
密 码:<input type="password" id="password"><br>
<input type="button" value="登录" id="btn1">
<input type="button" value="注册" id="btn2">
</body>
</html>
效果