Vue nodejs商城项目-登录模块
一、登录功能
后端server/routes/users.js
-
var User = require('./../models/users.js');
-
-
// 二级路由
-
// 登录接口
-
router.post("/login",function(req, res, next){
-
// 获取参数
-
var param = {
-
userName:req.body.userName,
-
userPwd:req.body.userPwd
-
}
-
User.findOne(param, function(err,doc){ // 根据用户名密码查找数据库
-
if(err){
-
res.json({
-
status:"1",
-
msg:err.message
-
})
-
}else{
-
if(doc){
-
res.cookie("userId",doc.userId,{
-
path:'/',
-
maxAge:100*60*60
-
});
-
// res.cookie("userName",doc.userName,{
-
// path:'/',
-
// maxAge:1000*60*60
-
// });
-
// req.session.user = doc;
-
res.json({
-
status:"0",
-
msg:'',
-
result:{
-
userName:doc.userName
-
}
-
})
-
}
-
}
-
})
-
})
添加代理config/index.js
-
proxyTable: {
-
'/users/*':{ // users/路由的下一级路由
-
target:'http://localhost:3000'
-
}
-
},
-
-
说明:如果是有三级路由,例'/users/cart/del',需要配置'/users/**';否则请求时会出现404错误。
前端NavHeader.vue
-
methods:{
-
login(){ // 点击登录
-
console.log("userName:"+this.userName)
-
if(!this.userName || !this.userPwd){
-
this.errorTip = true;
-
return
-
}
-
axios.post("/users/login",{
-
userName:this.userName,
-
userPwd:this.userPwd
-
}).then((response)=>{
-
let res = response.data;
-
if(res.status == "0"){
-
this.errorTip = false;
-
this.loginModalFlag = false;
-
this.nickName = res.result.userName;
-
}else{
-
this.errorTip = true;
-
}
-
})
-
}
-
}
二、登出功能
后端server/routes/users.j
-
/ 登出接口
-
router.post("/logout",function(req,res,next){
-
res.cookie("userId","",{
-
path:"/",
-
maxAge:-1 // 生命周期
-
})
-
res.json({
-
status:"0",
-
msg:'',
-
result:''
-
})
-
})
前端NavHeader.vue
-
methods:{
-
logOut(){ // 点击logout登出
-
axios.post("/users/logout").then((response)=>{
-
let res = response.data;
-
if(res.status== "0"){
-
this.nickName = '';
-
}
-
})
-
}
-
}
三、登录拦截功能
server/app.js
-
// 捕获登录状态
-
app.use(function(req,res,next){ // 进入路由之前优先进入function
-
if(req.cookies.userId){ // 有cookies,说明已经登录
-
next();
-
}else{
-
console.log("url:"+req.originalUrl);
-
if(req.originalUrl =='/users/login' || req.originalUrl == '/users/logout' || req.originalUrl == '/goods/list'){ // 未登录时可以点击登录login登出logout和查看商品列表
-
next();
-
}else{
-
res.json({
-
status:'1001',
-
msg:'当前未登录',
-
result:''
-
})
-
}
-
}
-
})
四、校验登录
server/routes/users.js
-
登录接口添加userName的cookie
-
res.cookie("userName",doc.userName,{
-
path:'/',
-
maxAge:1000*60*60
-
});
-
-
// 校验是否登录
-
router.get("/checkLogin",function(req,res,next){
-
if(req.cookies.userId){
-
res.json({
-
status:'0',
-
msg:'',
-
result:req.cookies.userName || ''
-
});
-
}else{
-
res.json({
-
status:'1',
-
msg:'未登录',
-
result:''
-
})
-
}
-
})
src/components/NavHeader.vue
-
mounted(){
-
this.checkLogin();
-
},
-
methods:{
-
checkLogin(){ // 检查是否登录
-
axios.get("/users/checkLogin").then((response)=>{
-
let res = response.data;
-
if(res.status == '0'){
-
this.nickName = res.result;
-
}
-
})
-
}
-
}