目 录CONTENT

文章目录

原生JS操作Cookie

Hello!你好!我是村望~!
2023-10-22 / 0 评论 / 0 点赞 / 111 阅读 / 1,229 字
温馨提示:
我不想探寻任何东西的意义,我只享受当下思考的快乐~

原生JS操作Cookie

1.什么是cookie

HTTP协议本身是无状态的。什么是无状态呢,即服务器无法判断用户身份。Cookie实际上是一小段的文本信息(key-value格式)。客户端向服务器发起请求,如果服务器需要记录该用户状态,就使用response向客户端浏览器颁发一个Cookie。客户端浏览器会把Cookie保存起来。当浏览器再请求该网站时,浏览器把请求的网址连同该Cookie一同提交给服务器。服务器检查该Cookie,以此来辨认用户状态。

打个比方,我们去银行办理储蓄业务,第一次给你办了张银行卡,里面存放了身份证、密码、手机等个人信息。当你下次再来这个银行时,银行机器能识别你的卡,从而能够直接办理业务。

2.cookie机制

当用户第一次访问并登陆一个网站的时候,cookie的设置以及发送会经历以下4个步骤:

1.客户端发送一个请求到服务器 -->

2.服务器发送一个HttpResponse响应到客户端,其中包含Set-Cookie的头部 -->

3.客户端保存cookie,之后向服务器发送请求时,HttpRequest请求中会包含一个Cookie的头部 -->

4.服务器返回响应数据

image-20210605104427047

img

3.cookie属性项

属性项 属性项介绍
NAME=VALUE 键值对,可以设置要保存的 Key/Value,注意这里的 NAME 不能和其他属性项的名字一样
Expires 过期时间,在设置的某个时间点后该 Cookie 就会失效
Domain 生成该 Cookie 的域名,如 domain=“www.baidu.com
Path 该 Cookie 是在当前的哪个路径下生成的,如 path=/wp-admin/
Secure 如果设置了这个属性,那么只会在 SSH 连接时才会回传该 Cookie

4.Javascript操作Cookie

document.cookie

通过document.cookie获取到的是由全部cookie组成的字符串

 const cookieStr = document.cookie;
 console.log(cookieStr);

/*
NMTID=00O6wWW-eMqJTKNrUtnqW4N0PP-ii8AAAF5yCKtIw; __remember_me=true; name=1; name1=1; MUSIC_U=38232f0f675f8ec6e5bdb26e8a0f94c786d28c3331a535134d05358a6c52501433a649814e309366; __csrf=6a3b3880e3d9384ca1288ca4b5bd97e0
*/

可以看到每一组Cookie是由分号(;)隔开,也有空格在里面,每一组cookie的键值是用等号(=)相连

4.1 将Cookie字符串转换为JS中的对象

getCookieObject() {
    const cookieStr = document.cookie;
    const cookies = cookieStr.split(";").reduce((acc, current, index) => {
        const subStringIndex = current.indexOf("=");
        const key = current.substr(0, subStringIndex).trim();
        const value = current.substr(subStringIndex + 1).trim();
        return Object.assign(acc, {[key]: value});
    }, {})
    return cookies;
}
{
    "NMTID":"00O6wWW-eMqJTKNrUtnqW4N0PP-ii8AAAF5yCKtIw",
    "__remember_me":"true","name":"1",
    "name1":"1",
    "MUSIC_U":"38232f0f675f8ec6e5bdb26e8a0f94c786d28c3331a535134d05358a6c52501433a649814e309366",
    "__csrf":"6a3b3880e3d9384ca1288ca4b5bd97e0"
}

4.2 JS写入Cookie

  • key表示写入的Cookie的Key键值
  • value表示对应的值
  • expires 为过期时间,这里用的单位为小时!
setCookie(key, value, expires) {
    if (!(typeof expires == "number") || expires < 0) {
        throw new Error("The expiration time must be a number and greater than 0");
    } else {
        let writeRes;
        const nowTime = new Date().getTime()
        const expiresDate = new Date(nowTime + expires * 60 * 60 * 1000);
        document.cookie = `${key}=${value};expires=${expiresDate}`
        let timer = setTimeout(() => {
            writeRes = this.getCookie(key)
            console.log(writeRes)
            clearTimeout(timer);
            timer = null;
        })
        return writeRes;
    }
}

测试使用一下

cookieAction.setCookie("token", "test.token", 2);

image-20210605112908802

键值+过期时间都写入成功了!

4.3 JS修改Cookie

其实就是key一样的情况,value重新写入!

cookieAction.setCookie("token", "test.token2", 2);

image-20210605113052668

4.4 JS删除Cookie

其实就是把过期时间设置为已经过去的时间越远越好

removeCookie(key) {
    console.log(key)
    if (!this.getCookie(key)) return;
    const nowTime = new Date().getTime()
    const expiresDate = new Date(nowTime - 365 * 24 * 60 * 60 * 1000);
    document.cookie = `${key}=${""};expires=${expiresDate};`
}

5.完整代码

class CookieAction {
    cookieObject;

    constructor() {
        this.cookieObject = this.getCookieObject();
    }

    /*
    @name: getCookieStr
    @description:处理Cookie字符串为对象
    */
    getCookieObject() {
        const cookieStr = document.cookie;
        const cookies = cookieStr.split(";").reduce((acc, current, index) => {
            const subStringIndex = current.indexOf("=");
            const key = current.substr(0, subStringIndex).trim();
            const value = current.substr(subStringIndex + 1).trim();
            return Object.assign(acc, {[key]: value});
        }, {})
        return cookies;
    }

    /*
    @name: getCookie
    @description: 根据Key获取Cookie
    */
    getCookie(key) {
        if (!(key in this.getCookieObject)) return false;
        return this.getCookieObject[key]
    }

    /*
    @name: writeCookie
    @description: 写入Cookie
    @params:key cookie的键!;value cookie 要写入的值!;expires 过期时间毫秒(ms)!
    */
    setCookie(key, value, expires) {
        if (!(typeof expires == "number") || expires < 0) {
            throw new Error("The expiration time must be a number and greater than 0");
        } else {
            const nowTime = new Date().getTime()
            const expiresDate = new Date(nowTime + expires * 60 * 60 * 1000);
            document.cookie = `${key}=${value};expires=${expiresDate}`
        }
    }

    /*
    @name:removeCookie
    @description:删除Cookie(过期时间设置为已经过去的时间)
    */
    removeCookie(key) {
        if (!this.getCookie(key)) return;
        const nowTime = new Date().getTime()
        const expiresDate = new Date(nowTime - 365 * 24 * 60 * 60 * 1000);
        document.cookie = `${key}=${""};expires=${expiresDate};`
    }
}

const cookieAction = new CookieAction();
export default cookieAction;
0

评论区