Vue+Node实现的商城用户管理功能示例
本文实例讲述了Vue+Node实现的商城用户管理功能。分享给大家供大家参考,具体如下:
1、用户登陆
前端将用户输入的用户名密码post发送到后端,如果返回status=0,代表登陆成功,将hasLogin置为true,控制页面登陆按钮不显示,并显示返回的用户名nickname
login(){
if(!this.username||!this.password){
this.errMsg="请输入用户名与密码!";
this.errShow=true;
}else{
axios.post('/users/login',{
username:this.username,
password:this.password
}).then((response,err)=>{
letres=response.data;
if(res.status===0){
this.hasLogin=true;
this.nickname=res.result;
this.closeLogin();
}else{
this.errShow=true;
this.errMsg=res.msg;
}
})
}
},
后端根据前端传来的用户名、密码在数据库中查找指定条目,查询成功返回status=0,并设置res的cookie保存用户名与Id
router.post('/login',function(req,res,next){
letusername=req.body.username;
letpassword=req.body.password;
letparams={
userName:username,
userPwd:password
};
user.findOne(params,(err,userDoc)=>{
"usestrict";
if(err){
res.json({
status:1,
msg:err.message
})
}else{
if(userDoc){
//登陆成功后设置res.cookie与req.session
res.cookie('userId',userDoc.userId,{
maxAge:1000*60*60
});
res.cookie('userName',userDoc.userName,{
maxAge:1000*60*60
});
res.json({
status:0,
msg:'登陆成功',
result:userDoc.userName
});
}else{
res.json({
status:1,
msg:'用户名或密码错误!'
});
}
}
})
});
2、服务器Express全局拦截
一些内容在用户未登录是无法访问的,需要服务器对非法请求进行拦截。在nodejs中请求先到达app.js文件,然后再转发到指定路由。在转发之前,可以先对用户登陆状态进行判断,如果cookies中有设置userId,表明已登陆,执行下一步next()。如果未登录,只可以访问指定的路由路径,由req.originalUrl判断是否等于或包含允许的访问路径,用户在未登录时可以访问登陆页面与商品列表页面。如果访问其他路径则返回错误信息“用户未登录”:
//全局拦截
app.use(function(req,res,next){
if(req.cookies.userId)next();//已登陆
//未登录,只能访问登录与商品页面
elseif(req.originalUrl==='/users/login'||req.originalUrl.indexOf('/goods')>-1)next();
else{
res.json({
status:3,
msg:'用户未登录'
})
}
});
//路由跳转
app.use('/',index);
app.use('/users',users);
app.use('/goods',goods);
3、校验登陆
在页面加载完成后,需要判断用户是否已经登陆过了,前端向后端发出checkLogin的请求,后端根据cookie中的userId是否设置,返回判断信息,如果登陆则不需要用户再次手动登陆了
router.get('/checkLogin',(req,res)=>{
"usestrict";
if(req.cookies.userId){//设置了cookie,用户已登陆
res.json({
status:0,
msg:"登录成功",
username:req.cookies.userName
})
}else{
res.json({
status:3,
msg:"未登录"
})
}
});
4、登出
用户的登出操作就是将cookie信息去除,即在后台将用户cookie的有效期置为0
router.get('/logout',(req,res)=>{
"usestrict";
res.cookie('userId','',{maxAge:0});
res.cookie('userName','',{maxAge:0});
res.json({
status:0,
msg:'登出成功!'
})
});
希望本文所述对大家node.js程序设计有所帮助。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。