1.动态服务器
静态服务器和动态服务器的主要区别是什么?
是否动态访问了数据库,访问了数据库的就是动态服务器
前端需要了解一点数据库的知识,所以,用json文件充当数据库,来模拟一下
json文件代码:
[
{"id":"1","name":"Frank","password":"123456","age":"18"},
{"id":"2","name":"Red","password":"123456","age":"18"}
]
读取、添加、删除、写入json文件代码:
const fs = require("fs")
//读数据库
const usersString = fs.readFileSync('./db/users.json').toString();
const usersArray = Json.parse(usersString);
//写数据库
const user3 = {id: 3,name: "tom",password: "123456",age: 20}
usersArray.push(user3);
const string = JSON.stringify(usersArray)
fs.writeFileSync('./db/users.json', string)
读取users数据:
先fs.readFileSync('./db/users.json').toString();
再Json.parse(usersString)一下(反序列化),得到数组
储存users数据:
先JSON.stringify(usersArray)(序列化),得到字符串
然后将string写入fs.writeFileSync('./db/users.json', string)
2.用户注册简易实现
register注册页主要代码:
<form id="registerForm">
<div>
<label for="">用户名:<input type="text" name="name" ></label>
</div>
<div>
<label for="">密码:<input type="password" name="password" ></label>
</div>
<div>
<button type="submit">注册</button>
</div>
</form>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script>
const $form = $('#registerForm')
$form.on('submit', (e) => {
e.preventDefault(); //阻止默认事件
const name = $form.find('input[name=name]').val(); //获取用户名
const password = $form.find('input[name=password]').val(); //获取注册密码
console.log(name, password);
$.ajax({ //引入Ajax
method: 'POST', //发送post请求,如果发送get请求,发送的内容就在请求头上了
contentType: 'text/json;charset=UTF-8', //告诉服务器上传的是Json字符串
url: '/register',
data: JSON.stringify({
name,
password
})
}).then(
() => {
alert('注册成功')
location.href = '/sign_in.html'
},
() => {
})
})
</script>
用post上传json字符串,但是服务器怎么知道是json字符串呢,通过contentType设置,来告诉他
后端server.js主要代码:
if (path === '/register' && method === 'POST') {
response.setHeader("Content-Type", "text/html; charset=utf-8");
const userArray = JSON.parse(fs.readFileSync("./db/users.json"));
const array = [];
request.on("data", chunk => {
array.push(chunk);
});
request.on("end", () => {
const string = Buffer.concat(array).toString();
const obj = JSON.parse(string);
const lastUser = userArray[userArray.length - 1];
const newUser = {
// id 为最后一个用户的 id + 1
id: lastUser ? lastUser.id + 1 : 1,
name: obj.name,
password: obj.password
};
userArray.push(newUser);
fs.writeFileSync("./db/users.json", JSON.stringify(userArray));
response.end()
});
}
获取post里面内容并存储到json文件中
2.用户登陆简易实现
sign_in登陆页代码:
<form id="signInForm">
<div>
<label>用户名 <input type="text" name="name"></label>
</div>
<div>
<label>密码 <input type="password" name="password"></label>
</div>
<div>
<button type="submit">登录</button>
</div>
</form>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script>
const $form = $('#signInForm')
$form.on('submit', (e) => {
e.preventDefault()
const name = $form.find('input[name=name]').val()
const password = $form.find('input[name=password]').val()
$.ajax({
method: 'POST',
url: '/sign_in',
contentType: 'text/json; charset=UTF-8',
data: JSON.stringify({
name,
password
})
}).then(() => {
alert('登录成功')
location.href = '/home.html'
}, () => {})
})
</script>
和注册页面差别不大
后端server.js主要代码:
if (path === "/sign_in" && method === "POST") {
const userArray = JSON.parse(fs.readFileSync("./db/users.json"));
const array = [];
request.on("data", chunk => {
array.push(chunk);
});
request.on("end", () => {
const string = Buffer.concat(array).toString();
const obj = JSON.parse(string); // name password
const user = userArray.find(
user => user.name === obj.name && user.password === obj.password
);
if (user === undefined) {
response.statusCode = 400;
response.setHeader("Content-Type", "text/json; charset=utf-8");
} else {
response.statusCode = 200;
}
response.end()
});
}
4.标记用户登陆,cookie,session
上面完成和登陆页面,但是我们发现,通过登陆进入home页面,和直接输入网址进入登陆页面发送的请求是一样的,所以我们需要用cookie标记用户
cookie定义:
- cookie是服务器下发给浏览器的一段字符串
- 浏览器必须保存这个cookie(除非用户删除)
- 之后发起同级二级域名请求时,浏览器必须附上cookie
怎么给浏览器发cookie呢
if (path === "/sign_in" && method === "POST") {
const userArray = JSON.parse(fs.readFileSync("./db/users.json"));
const array = [];
request.on("data", chunk => {
array.push(chunk);
});
request.on("end", () => {
const string = Buffer.concat(array).toString();
const obj = JSON.parse(string); // name password
const user = userArray.find(
user => user.name === obj.name && user.password === obj.password
);
if (user === undefined) {
response.statusCode = 400;
response.setHeader("Content-Type", "text/json; charset=utf-8");
} else {
response.statusCode = 200;
response.setHeader('Set-Cookie', 'logined=1')//加上这一句话,
在浏览器上的请求响应上就会出现cookie
}
response.end()
});
}
在server.js home里面读取一下cookie
if (path === "/home.html") {
response.end('home')
const cookie = request.headers["cookie"];
console.log(cookie)
}
根据cookie判断登陆状态
if (path === "/home.html") {
response.end('home')
const cookie = request.headers["cookie"];
if(cookie === "logined=1"){
const homeHtml = fs.readFileSync("./public/home.html").toString();
const string = homeHtml.replace('{{loginStatus}}','已登录')
response.write(string)
}else{
const homeHtml = fs.readFileSync("./public/home.html").toString();
const string = homeHtml.replace('{{loginStatus}}','未登录')
response.write(string)
}
}
通过cookie .split(";") .filter(s => s.indexOf("session_id=") >= 0)[0].split("=")[1],可以得到用户登陆的id,然后直接替换到页面就可以了,但是用户可以在cookies里面直接修改id
防止用户篡改id
- 把用户信息放在服务器的X里面,再给信息一个随机id
- 把随机id发给浏览器
- 后端下次读取id时通过x[id]获取用户信息
- 为什么用户无法篡改id(因为id很长,且是随机的)
- x是什么,是文件
- 这个x又被叫做session(会话)