cookie 和 session
cookie 和 session 都是普遍用来跟踪浏览用户身份的会话方式。
cookie 和 session 区别
- cookie 数据存放在客户端,session 数据放在服务器端。
- cookie 本身并不安全,考虑到安全应当使用 session。
- session 会在一定时间内保存在服务器上。如果访问量比较大,会比较消耗服务器的性能。考虑到减轻服务器性能方面的开销,应当使用 cookie 。
- 单个 cookie 保存的数据不能超过 4K,很多浏览器都限制一个域名最多保存 50 个 cookie。 将登陆信息等重要信息存放为 session、其他信息如果需要保留,可以放在 cookie 中。
session 主要是服务端使用处理数据,本文主要针对前端技术故不多赘述。
cookie 的使用
cookie 可通过 document.cookie
获取全部 cookie。它是一段字符串,是键值对的形式。操作起来有些麻烦,可引入封装好的库进行使用,比如 js-cookie
。API 也很简洁:
Cookies.set("name", "value", { expires: 7 }); // 设置一个cookie,7天后失效
Cookies.get("name"); // => 'value'
Cookies.remove("name");
js-cookie.mjs源码
function extend () {
var result = {}
for (var i = 0; i < arguments.length; i++) {
var attributes = arguments[i]
for (var key in attributes) {
result[key] = attributes[key]
}
}
return result
}
function decode (s) {
return s.replace(/(%[\dA-F]{2})+/gi, decodeURIComponent)
}
function init (converter) {
function set (key, value, attributes) {
if (typeof document === 'undefined') {
return
}
attributes = extend(api.defaults, attributes)
if (typeof attributes.expires === 'number') {
attributes.expires = new Date(Date.now() + attributes.expires * 864e5)
}
if (attributes.expires) {
attributes.expires = attributes.expires.toUTCString()
}
value = converter.write
? converter.write(value, key)
: encodeURIComponent(String(value)).replace(
/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,
decodeURIComponent
)
key = encodeURIComponent(String(key))
.replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent)
.replace(/[()]/g, escape)
var stringifiedAttributes = ''
for (var attributeName in attributes) {
if (!attributes[attributeName]) {
continue
}
stringifiedAttributes += '; ' + attributeName
if (attributes[attributeName] === true) {
continue
}
// Considers RFC 6265 section 5.2:
// ...
// 3. If the remaining unparsed-attributes contains a %x3B (";")
// character:
// Consume the characters of the unparsed-attributes up to,
// not including, the first %x3B (";") character.
// ...
stringifiedAttributes += '=' + attributes[attributeName].split(';')[0]
}
return (document.cookie = key + '=' + value + stringifiedAttributes)
}
function get (key) {
if (typeof document === 'undefined' || (arguments.length && !key)) {
return
}
// To prevent the for loop in the first place assign an empty array
// in case there are no cookies at all.
var cookies = document.cookie ? document.cookie.split('; ') : []
var jar = {}
for (var i = 0; i < cookies.length; i++) {
var parts = cookies[i].split('=')
var cookie = parts.slice(1).join('=')
if (cookie.charAt(0) === '"') {
cookie = cookie.slice(1, -1)
}
try {
var name = decode(parts[0])
jar[name] =
(converter.read || converter)(cookie, name) || decode(cookie)
if (key === name) {
break
}
} catch (e) {}
}
return key ? jar[key] : jar
}
var api = {
defaults: {
path: '/'
},
set: set,
get: get,
remove: function (key, attributes) {
set(
key,
'',
extend(attributes, {
expires: -1
})
)
},
withConverter: init
}
return api
}
export default init(function () {})
localStorage 和 sessionStorage
在 web 本地存储场景上,cookie 的使用受到种种限制,最关键的就是存储容量太小和数据无法持久化存储。
在 HTML 5 的标准下,出现了 localStorage 和 sessionStorage 供我们使用。
- cookie、localStorage 以及 sessionStorage 的异同点:
分类 | 生命周期 | 存储容量 | 存储位置 |
---|---|---|---|
cookie | 默认保存在内存中,随浏览器关闭失效(如果设置过期时间,在到过期时间后失效) | 4KB | 保存在客户端,每次请求时都会带上 |
localStorage | 理论上永久有效的,除非主动清除。 | 4.98MB(不同浏览器情况不同,safari 2.49M) | 保存在客户端,不与服务端交互。节省网络流量 |
sessionStorage | 仅在当前网页会话下有效,关闭页面或浏览器后会被清除。 | 4.98MB(部分浏览器没有限制) | 同上 |
- 应用场景:localStorage 适合持久化缓存数据,比如页面的默认偏好配置等;sessionStorage 适合一次性临时数据保存。
WebStorage( localStorage 和 sessionStorage ) 本身就提供了比较好用的方法:
localStorage.setItem("name", "value");
localStorage.getItem("name"); // => 'value'
localStorage.removeItem("name");
localStorage.clear(); // 删除所有数据
sessionStorage.setItem("name", "value");
sessionStorage.setItem("name");
sessionStorage.setItem("name");
sessionStorage.clear();
复制代码
注意事项:
- localStorage 写入的时候,如果超出容量会报错,但之前保存的数据不会丢失。
- localStorage 存储容量快要满的时候,getItem 方法性能会急剧下降。
- web storage 在保存复杂数据类型时,较为依赖
JSON.stringify
,在移动端性能问题比较明