佳宸学习和分享笔记的地方

0%

vue.js商城项目(六)登陆

vue.js商城项目(六)登陆

在User.js进行一个比较密码的函数封装

1
2
3
4
5
6
7
8
9
10
11
userSchema.methods = {
//密码比对的方法
comparePassword: (_password, password) => {
return new Promise((resolve, reject) => {
bcrypt.compare(_password, password, (err, isMatch) => {
if (!err) resolve(isMatch)
else reject(err)
})
})
}
}

进行接口的封装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
router.post('/login', async(ctx) => {
//得到前端传递过来的数据
let loginUser = ctx.request.body
console.log(loginUser)
let userName = loginUser.userName
let password = loginUser.password
//引入User的model
const User = mongoose.model('User')
//查找用户名是否存在,如果存在开始比对密码
await User.findOne({ userName: userName }).exec().then(async(result) => {
console.log(result)
if (result) {
//console.log(User)
//当用户名存在时,开始比对密码
let newUser = new User() //因为是实例方法,所以要new出对象,才能调用
await newUser.comparePassword(password, result.password)
.then((isMatch) => {
//返回比对结果
ctx.body = { code: 200, message: isMatch }
})
.catch(error => {
//出现异常,返回异常
console.log(error)
ctx.body = { code: 500, message: error }
})
} else {
ctx.body = { code: 200, message: '用户名不存在' }
}

}).catch(error => {
console.log(error)
ctx.body = { code: 500, message: error }
})
})

前台axios请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
  this.$axios
.post(url.login, {
userName: this.username,
password: this.password
})
.then(response => {
console.log(response);
if (response.data.code == 200 && response.data.message) {
new Promise((resolve, reject) => {
localStorage.userInfo = { userName: this.username };
setTimeout(() => {
resolve();
}, 500);
})
.then(() => {
Toast.success("登录成功");
this.$router.push("/");
})
.catch(err => {
Toast.fail("登陆状态保存失败");
});
}
else {
Toast.fail("登录失败");
this.openLoading = false;
}
})
.catch(error => {
console.log(error);
Toast.fail("登录失败");
this.openLoading = false;
});
},

验证登陆自动跳转

1
2
3
4
5
created(){
if(localStorage.userInfo){
Toast.success('已经登陆')
this.$router.push('/')
}