Vue+Node+MongoDB实现商城系统——11章:登录功能及全局拦截

一、登录

1、前端请求

var axios = require('axios'),
    qs = require('qs');
export default {
    ...
    methods:{
        login(){
            var userName = this.userName,
                userPwd = this.userPwd;
            axios.post('/login',qs.stringify({
                userName:userName,
                userPwd:userPwd
            }),{
                header:{
                    'Content-Type':'x-www-form-urlencoded'
                }
            }).then(res=>{
                if(res.status=='0'){

                }else{
                    console.log('登录失败')
                }
            })
        }
    }
}

2、后台接口

  • 后台写入cookie到客户端:res.cookie(key,value,optiions).其中options的maxAge为超期时间,path为cookie位置
  • 后台清cookie,可以通过重写的方式,res.cookie(key,value,options),其中options的maxAge设置为
router.post('/login',function(req,res,next){
    var userName = req.body.userName,
        userPwd= req.body.userPwd;
    User.findOne({userName:userName},function(err,doc){
        if(err){
            res.json({
                status:1,
                msg:err.message
            })
        }else{
            var findPwd = doc.userPwd;
            if(doc){
                if(findPwd==userPwd){
                    // 在客户端存cookie,因为cookie可以伪造,所以还可以存session
                    res.cookie("userId",doc.userId,{
                        path:'/',
                        maxAge:1000*60*60
                    });
                     //存session,因为session是从客户端发送的,所以这里用req
                   // req.session.user = doc;
                    res.json({
                        status:0,
                        msg:'',
                        result:{
                            userName:doc.userName
                        }
                    })
                }
            }
        }
    })
})

二、购物车

2.1 购物车列表

说明:
- 前面通过login,将用户userId存到了cookie中,而在购物车页,当页面加载时,就请求拿取cartList购物车列表
- 后端拿cookie: 用到中间件cookie-parser,它会将客户端的cookie字符串转换为对象形式,通过req.cookies.userId调用
- 根据userId查询数据, Model.findOne({‘userId’:userId},fn)
- 前端拿到返回数据后,渲染

2.2 删除购物车中的商品

说明:
- 绑定删除事件,传入商品productId到后端进行删除操作
- 后端,Model.update({userId:userId},{pull:{'cartList':{'productId':productId}}}) 删除, pull:{'cartList':{'productId':productId}}}) 删除, pull用于删除,$push用于添加。
- 前端拿到删除结果后,再次渲染列表

User.update({userId:userId},{$pull:{
    cartList:{
        {
            productId:productId
        }
    }
}})

你可能感兴趣的:(前端框架)