- 每次请求都会带上 cookie 到服务端, 有些跨域的请求, 服务端不允许携带 cookie 的话就会报错
- cookie 中的数据特别大的话, 会导致请求速度特别慢
javascript
(function () {
var cookieMgr = {};
// 获取 cookie
cookieMgr.get = function (key) {
var cookies = document.cookie.split("; ");
var item;
for (var i = 0; i < cookies.length; i++) {
item = cookies[i].split("=");
if (item[0] === key) {
return item[1];
}
}
};
// 设置cookie
cookieMgr.set = function (key, val, expired) {
document.cookie = String(key) + "=" + val + ";max-age=" + expired;
return this;
};
// 删除cookie
cookieMgr.delete = function (key) {
return this.set(key, "", -1);
};
// 判断是否有某个值
cookieMgr.has = function (key) {
return Boolean(this.get(key));
};
// 能获取到就没过期, 过期了就无法获取到
cookieMgr.isExpired = function (key) {
return cookieMgr.has(key);
};
Object.freeze && Object.freeze(cookieMgr);
return cookieMgr;
})();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40