目的:
前端保存token和用戶名
過程:
1、前端登錄JS代碼
// 請求成功後,寫入 access_token
layui.sessionData(setter.tableName, {
key: "data"
, value: [{
'token': res.data[0]['token']
}, {
'name': res.data[1]['name']
}
]
});
// 登入成功的提示與跳轉
layer.msg('登入成功', {
offset: '15px'
, icon: 1
, time: 1000
}, function () {
//跳轉路徑前面要加/,要不然路徑不準確,根據自己的文件路徑寫
window.location = "/views/index.html";
});
2、後端返回數據
{
"code": 0,
"msg": "success",
"data": [
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1ODQ1ODg3MDB9.SZB8HDlWsqduMMDL0eQWfFiO0dUbg58Q0yfeW-mNFf8"
},
{
"name": "admin"
}
]
}
3、前端JS校驗Token代碼
$(document).ready(function () {
// 如果會話性存儲 數據爲空,返回登錄界面
if (layui.sessionData('layuiAdmin') === {}) {
location.href = 'login.html'; //登錄主頁
} else {
// 如果會話性存儲data鍵爲空
if (layui.sessionData('layuiAdmin').data != null) {
// 如果會話性存儲data鍵第一個鍵token爲空
if (layui.sessionData('layuiAdmin').data[0]['token'] === '') {
// 返回到登錄界面
location.href = 'login.html'; //登錄主頁
}
}
// 返回登錄界面
else{
location.href = 'login.html'; //登錄主頁
}
}
});
var lastTime = new Date().getTime();
var currentTime = new Date().getTime();
// var timeOut = 30 * 60 * 1000; //設置超時時間: 30分
var timeOut = 15 * 60 * 1000; //設置超時時間: 15分
window.onload = function () {
window.document.onmousedown = function () {
localStorage.setItem("lastTime", new Date().getTime());
}
};
function checkTimeout() {
currentTime = new Date().getTime(); //更新當前時間
lastTime = localStorage.getItem("lastTime");
// console.log(currentTime - lastTime);
// console.log(timeOut);
if (currentTime - lastTime > timeOut) { //判斷是否超時
// console.log("超時");
location.href = 'login.html'; //登錄頁面
}
}
/* 定時器 間隔30秒檢測是否長時間未操作頁面 */
window.setInterval(checkTimeout, 30000);