前后端分离前端使用localJStorage取代cookies
前后端分离后,面临着pc端和移动端的兼容问题,为了使用跨终端前端技术同时保证相同的开发接口,决定放弃APP侧没有的cookies,使用localStorage,并做了一些简单封装,使其和cookies类似:
const expirefix = "__expires__"; /** * @desc 在localStorage基础上封装支持过期时间的storage,代替cookie。 * @author zhiletu.com * @version 1.0 */ export default class wldosStorage { constructor(props) { this.props = props || {} this.source = this.props.source || window.localStorage this.init(); } init(){ /** * @desc 初始化localstorage * @param {String} key 键 * @param {String} value 值,若存储数组、对象,需要通过JSON.stringify转换为json字符串 * @param {String} expired 过期时间,以分钟为单位 */ const reg = new RegExp(expirefix); const data = this.source; const list = Object.keys(data); if(list.length > 0){ list.map((item)=>{ const { key } = item; if( !reg.test(key)){ const now = Date.now(); const expires = data[`${key}${expirefix}`]||Date.now+1; if (now >= expires ) { this.remove(key); }; }; return key; }); }; } remove(key) { const data = this.source; const value = data[key]; delete data[key]; delete data[`${key}${expirefix}`]; return value; } get(key) { /** * @desc 从localstorage获取项 * @param {String} key 键 * @param {String} expired 存储时为非必须字段,所以有可能取不到,默认为 Date.now+1 */ const { source } = this; const expired = source[`${key}${expirefix}`]||Date.now+1; const now = Date.now(); if ( now >= expired ) { this.remove(key); return undefined; } return source[key] ? JSON.parse(source[key]) : source[key]; } set(key, value, expired) { /** * @desc 设置localStorage项 * @param {String} key 键 * @param {String} value 值 * @param {Number} expired 过期时间,以分钟为单位,非必填 */ const { source } = this; source[key] = JSON.stringify(value); if (expired){ source[`${key}${expirefix}`] = Date.now() + 1000*60*expired }; return value; } } 你可以像使用cookies一样操作上面的storage,设置token等前后端权限认证相关的参数,并支持设置超时过期。 比如在Ant design pro react v4框架中设置权限参数的方法可以如下使用上面的工具类:
/** * @desc 通过response对象获取服务端返回的认证信息并缓存本地。 * @param response 服务端响应 */ export function setAuthority(response) { const inHalfHours = 30; // 过期时间,单位分钟 const inTwoHours = 120; const { currentAuthority : authority } = response; const proAuthority = typeof authority === 'string' ? [authority] : authority; wldosStorage.set('wldos-authority', JSON.stringify(proAuthority), inHalfHours); wldosStorage.set('accessToken', response.token.accessToken, inHalfHours); wldosStorage.set('refreshToken', response.token.refreshToken, inTwoHours); reloadAuthorized(); }
声明: 除非转自他站(如有侵权,请联系处理)外,本文采用 BY-NC-SA 协议进行授权 | 嗅谱网
转载请注明:转自《前后端分离前端使用localJStorage取代cookies》
本文地址:http://www.xiupu.net/archives-10885.html
关注公众号:
微信赞赏
支付宝赞赏