1.将token存储在localstorage中的处理
//设置一个固定的key值
const KEY='Authorization'
//暴露三个方法
//设置token
export function setToken(token){
window.localStorage.setItem(KEY,token);
}
//获取token
export function getToken(){
return window.localStorage.getItem(KEY);
}
//删除token
export function removeToken(){
//根据key,删除指定的值
window.localStorage.removeItem(KEY);
}
2.将token存储在Cookie中的处理
/*
* @func setCookie
* @explain 设置cookie里的值
*/
export function setCookie(name, value, iDay) {
let oDate = new Date();
oDate.setDate(oDate.getDate() + iDay);
document.cookie = name + '=' + value + ';expires=' + oDate;
}
/*
* @func getCookie
* @explain 获取cookie里的值
*/
export function getCookie(cookieName) {
var strCookie = document.cookie;
var arrCookie = strCookie.split("; ");
for(var i = 0; i < arrCookie.length; i++){
var arr = arrCookie[i].split("=");
if(cookieName == arr[0]){
return arr[1];
}
}
return "";
}
/*
* @func removeCookie
* @explain 删除cookie里的值
*/
export function removeCookie(name) {
setCookie(name, 1, -1);
}
上面封装好的工具函数,在需要使用时直接导入函数调用即可,示例如图: