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实现网站语言切换