Cookie的属性-3 与 Cookie 的封装-1

Cookie的属性-3     

  Cookie的名称(Name)和值(Value)  
  失效(到期)时间
  Domain 域
  Path路径
  HttpOnly

    设置了 HttpOnly  属性Cookie 不能通过JS去访问  
  Secure  安全标志

     Secure限定了只有在使用了Https而不是http的情况下可以发送给服务端

    Domain、path、Secuer 都要满足条件,还不能过期 Cookie 才能随着请求发送到服务器端

          

    

Cookie 的封装-1

    封装Cookie

      set

      get
      remove  

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Cookie的封装</title>
</head>
<body>
    <script type="module" src="js/cookie.js">
      import{set,get,remove} from './js/cookie.js';   
        set('username','alex');
        set('username','zs');
        set('age',18);    
        set('用户名','张三');        
        
        
        set('sex','male',{
          maxAge:30 * 24 * 3600    
        });
        
        remove('username');
        remove('用户名')    
        
        console.log(get('username'));
        console.log(get('age'));    
        console.log(get('用户名'));
        console.log(get('sex'));                        
    </script>
</body>
</html>
复制代码

 

复制代码
// 写入
export const set = (name, value, { maxAge, domain, path, secure } = {}) => {
 
    let cookieText = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;
    if (typeof maxAge === 'nmber') {
        cookieText += `; max-age=${maxAge}`
    }
    if (domain) {
        cookieText += `; domain=${domain}`
    }
    if (path) {
        cookieText += `; path=${path}`
    }
    if (secure) {
        cookieText += `; secure`
    }
    document.cookie = cookieText
}
 
// 读取
export const get = name => {
    name = `${encodeURIComponent(name)}`;
    const cookies = document.cookie.split('; ');
    for (let item of cookies) {
        const [cookieName, cookieValue] = item.split('=');
        if (cookieName === name) {
            return decodeURIComponent(cookieValue)
        }
    }
    return undefined;
}
 
// 删除 
export const remove = (name, { domain, path } = {}) => {
    set(name, '', { domain, path, maxAge: -1 })
}
复制代码

 

 

 

 

 

    使用封装好的Cookie实现网站语言切换

posted @   zj勇敢飞,xx永相随  阅读(20)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示