Vue+Node实现的商城用户管理功能示例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Vue+Node实现的商城用户管理功能示例

theVicTory   2020-05-17 我要评论

本文实例讲述了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)=>{
       let res=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) {
 let username=req.body.username;
 let password=req.body.password;
 let params={
  userName:username,
  userPwd:password
 };
 user.findOne(params,(err,userDoc)=>{
  "use strict";
  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();    //已登陆
 //未登录,只能访问登录与商品页面
 else if(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)=>{
 "use strict";
 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)=>{
 "use strict";
 res.cookie('userId','',{maxAge:0});
 res.cookie('userName','',{maxAge:0});
 res.json({
  status:0,
  msg:'登出成功!'
 })
});

希望本文所述对大家node.js程序设计有所帮助。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们