欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue+Node實(shí)現(xiàn)的商城用戶管理功能示例

 更新時(shí)間:2019年12月23日 08:41:08   作者:theVicTory  
這篇文章主要介紹了Vue+Node實(shí)現(xiàn)的商城用戶管理功能,結(jié)合實(shí)例形式詳細(xì)分析了商城用戶管理的前臺登錄、校驗(yàn)、跳轉(zhuǎn)、退出等相關(guān)操作技巧,需要的朋友可以參考下

本文實(shí)例講述了Vue+Node實(shí)現(xiàn)的商城用戶管理功能。分享給大家供大家參考,具體如下:

1、用戶登陸

前端將用戶輸入的用戶名密碼post發(fā)送到后端,如果返回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;
       }
      })
     }
    },

后端根據(jù)前端傳來的用戶名、密碼在數(shù)據(jù)庫中查找指定條目,查詢成功返回status=0,并設(shè)置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){
    //登陸成功后設(shè)置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:'用戶名或密碼錯(cuò)誤!'
    });
   }
  }
 })
});

2、服務(wù)器Express全局?jǐn)r截

一些內(nèi)容在用戶未登錄是無法訪問的,需要服務(wù)器對非法請求進(jìn)行攔截。在nodejs中請求先到達(dá)app.js文件,然后再轉(zhuǎn)發(fā)到指定路由。在轉(zhuǎn)發(fā)之前,可以先對用戶登陸狀態(tài)進(jìn)行判斷,如果cookies中有設(shè)置userId,表明已登陸,執(zhí)行下一步next()。如果未登錄,只可以訪問指定的路由路徑,由req.originalUrl判斷是否等于或包含允許的訪問路徑,用戶在未登錄時(shí)可以訪問登陸頁面與商品列表頁面。如果訪問其他路徑則返回錯(cuò)誤信息“用戶未登錄”:

//全局?jǐn)r截
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:'用戶未登錄'
  })
 }
});

//路由跳轉(zhuǎn)
app.use('/', index);
app.use('/users', users);
app.use('/goods', goods);

3、校驗(yàn)登陸

在頁面加載完成后,需要判斷用戶是否已經(jīng)登陸過了,前端向后端發(fā)出checkLogin的請求,后端根據(jù)cookie中的userId是否設(shè)置,返回判斷信息,如果登陸則不需要用戶再次手動(dòng)登陸了

router.get('/checkLogin',(req,res)=>{
 "use strict";
 if(req.cookies.userId){      //設(shè)置了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程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評論