后臺:需要在得到登錄響應(yīng)后在數(shù)據(jù)庫里查詢是否存在用戶名和密碼,存在則登錄成功牙言,發(fā)送cookie和msg,否則登錄不成功怪得。
router.post('/api/login/checkAccount', function(req, res){
let userInfo = {
account:req.body.account,
password:getMD5Password(req.body.password)
}
console.log(userInfo)
models.Login.find(userInfo,function(err,detail){
console.log("checkAccount",detail)
if(detail.length){
res.cookie('login', 'username='+req.body.account, {
path: '/',
expires: new Date(Date.now() + 10000 * 60 * 60 * 24 * 7)
});
res.end(JSON.stringify({code:1,msg:'login successed'}));
console.log('login successed')
}else{
res.end(JSON.stringify({code:1,msg:'login failed'}));
}
})
});
前端咱枉,在頁面渲染時需要getcookie,如果cookie存在則顯示welcome,{{username}}徒恋,否則界面出現(xiàn)login表格蚕断,請求登錄。登錄后如果code正確做相應(yīng)的渲染入挣。
<template>
<div>
<div class="reg">
<input class="form-control" id="inputEmail3" placeholder="請輸入賬號" v-model="account">
<input type="password" class="form-control" id="inputPassword3" placeholder="請輸入密碼" v-model="password">
<button type="submit" class="btn btn-default" @click="login">注冊</button>
</div>
<div class="login" v-if="username==undefined">
<input class="form-control" id="inputEmail3" placeholder="請輸入賬號" v-model="account_login">
<input type="password" class="form-control" id="inputPassword3" placeholder="請輸入密碼" v-model="password_login">
<button type="submit" class="btn btn-default" @click="reg">登錄</button>
</div>
<div v-if="username!==undefined && username!==''">
<span>welcome {{username}}</span>
<button type="submit" class="btn btn-default" @click="logout">登出</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
account : '',
password : '',
account_login:'',
password_login:'',
username:''
}
},
mounted() {
if(this.getCookie("login")){
this.username = this.testKey(this.getCookie("login"),"username")
}else{
this.username = undefined
}
},
methods:{
login() {
this.$axios.post('/api/login/createAccount',{account:this.account,password:this.password}).then(res => {
console.log(res.data.code)
}).catch(err => {
})
},
reg() {
this.$axios.post('/api/login/checkAccount',{account:this.account_login,password:this.password_login}).then(res => {
console.log(res.data.code)
if(this.getCookie("login")){
this.username = this.testKey(this.getCookie("login"),"username")
}else{
this.username = undefined
}
}).catch(err => {
})
},
logout() {
this.username = undefined
this.delCookie("login")
},
delCookie:function (name){
var exp = new Date();
exp.setTime(exp.getTime() - 1);
var cval=this.getCookie(name);
if(cval!=null)
document.cookie= name + "="+cval+";expires="+exp.toGMTString();
},
getCookie:function(name){
var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
if(arr=document.cookie.match(reg))
return unescape(arr[2]);
else
return null;
},
testKey:function(str,key) {
let arr = str.split("&")
for(let i = 0; i < arr.length; i++) {
if(arr[i].split("=")[0] == key){
return arr[i].split("=")[1]
}
}
return ''
}
}
}
</script>