继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

localStorage也可以限时保存登录信息

花满楼的小前端a
关注TA
已关注
手记 42
粉丝 111
获赞 2213

localStorage用于持久化的存储;但是我想限时保存用户的登录信息,除了cookie和session,localStorage应该也可以做到;cookie字符长度有限制,不够6;session在后端保存;现在我要在前端保存用户信息,而不用每次后台判断或前端请求去判断;因为如果页面由前端输出,那么每次都得请求一次用户是否登录;

代码不多,大家都懂:

module.exports={
    age:0,
    maxAge:function (age) {
        this.age=age;
        return this;
    },
    set:function(name,json){
        localStorage.removeItem(name);
        json.__time=new Date().getTime();
        json.__age=this.age;
        localStorage.setItem(name,JSON.stringify(json));
        return this;
    },
    getInfo:function(name){
        var info=localStorage.getItem(name);
        return info?JSON.parse(info):null;
    },
    isExpired:function(name) {
        var logined=localStorage.getItem(name),
            _time=0,
            iTime=new Date().getTime(),
            timeLength=0;
        if (logined) {
            logined=JSON.parse(logined);
            _time=logined.__time;
            timeLength=iTime-_time;
            return timeLength>=logined.__age;
        }else {
            return true;
        }
    },
    isLogined:function(name,fn) {
        var user='',age=this.age;
        if (!this.isExpired(name)) {
            user=JSON.parse(localStorage.getItem(name));
        }else{
            localStorage.removeItem(name);
        }
        if (user) {
            fn&&fn(user);
        }else {
            fn&&fn();
        }
    }
};

使用:
var store=require('./modules/store');

前端在用户登录成功后保存基本信息:

store.maxAge(1000*60*60*24).set('userinfo',{
    name:'hf',
    age:'18'
 });

以JSON格式保存用户的信息name和age,字段名userinfo,保存时长为一天;

下次用户访问判断用户信息是否过期:

store.isExpired('userinfo');
//返回true|false

或者直接判断限定时间内是否登录了:

store.isLogined('userinfo',function(info){
        if (info) {
            console.log(info)
        }else {
            console.log(false)
        }
    });
//若在限定时间内登录了,回调用户信息;若没有登录,回调里做其他操作

获取登录信息,返回用户信息或null;也可以判断是否登录;

store.getInfo('userinfo');
//返回info或null

呵呵,就这么多了;简单的记录下,继续使用,继续填坑,继续完善;与君共勉!

原文来自:花满楼[localStorage也可以限时保存登录信息][1]

打开App,阅读手记
16人推荐
发表评论
随时随地看视频慕课网APP

热门评论

花满楼时心亦满。。。。。.

查看全部评论