5.2.1 描述:
/*
描述:
如果persons.json中含有对应的用户名和密码则提示登录成功,否则提示用户名和密码错误
*/
5.2.2 node文件
1)引入文件模块
let fs = require("fs");
2). form表单传递过来的数据。
let user = {
username: "xm1",
password: "1234"
};
3)创建实现登录功能的函数(推荐使用findIndex()方法)
function doLogin() {
// 读取./persons.json文件中的数据
let data = fs.readFileSync("./persons.json");
// 将读取的数据转为JSON对象的格式,存储在arr中
let arr = JSON.parse(data);
//循环遍历读取到的数组
/* //方法一:findIndex()
let tag = arr.findIndex((item) => {
return item.username == user.username && item.password == user.password;
});
if (tag == -1) {
console.log(`用户名或密码不正确`);
} else {
console.log("登录成功");
}
*/
let flag = false;
//方法二:for-in
for (let item of arr) {
if (item.username == user.username && item.password == user.password) {
flag = true;
console.log("登录成功");
}
}
if (flag == false) {
console.log(`用户名或密码不正确`);
}
}
4)调用登录函数
doLogin();