微信小程序中cookie的使用


配合另一篇文章的 微信小程序 wx.request 封装 使用。


在小程序中,异步请求wx.request最终调用的是微信内的异步请求方法,因此,小程序的不会存在自身内部的 cookie 逻辑。因此,如果请求需要使用 cookie 的话,需要我们自行插入wx.request的 headers 中。

下面简述一下我在项目中对 cookie 的处理。

  1. 封装 wx.request,然后在项目中都使用这个封装过的 request 方法
  2. 在封装的 requst 方法的回调内,执行以下的自定义 setCookie 方法。
  3. 在封装的 requst 方法的 headers,插入本地存储的 Cookie 内容(setCookie 方法内存至本地的 Cookie 数据)
request header
1
2
3
header: {
Cookie: wx.getStorageSync("Cookie");
}
  1. setCookie 方法内容如下, 这里为了方便,使用了 lodash,可自行使用原生 js
save cookies in responses
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
const setCookie = (data) => {
let cookieArr = [];
if (_.get(data, `header['Set-Cookie']`)) {
const cookieOriArr =
data.header["Set-Cookie"].match(/([\w\-.]*)=([^\s=]+);/g) || [];
_.forEach(cookieOriArr, (str) => {
if (!/path=|domain=|samesite=|max-age=/gi.test(str)) {
cookieArr.push(
_.endsWith(str, ";") ? str.substring(0, str.length - 1) : str
);
}
});

let localCookie = wx.getStorageSync("Cookie") || "";
let CookieObj = {};
const localCookieArr = localCookie.split(";") || [];

_.forEach(_.compact(localCookieArr), (item) => {
const cookieItem = item.split("=");
CookieObj[cookieItem[0]] = cookieItem[1];
});

_.forEach(_.compact(cookieArr), (item) => {
const cookieItem = item.split("=");
CookieObj[cookieItem[0]] = cookieItem[1];
});

const CookieStr = _.map(_.keys(CookieObj), (key) => {
return `${key}=${CookieObj[key]}`;
}).join(";");
wx.setStorageSync("Cookie", CookieStr);
}
};
  • 判断reponse中的header里面是否有Set-Cookie字段
  • 取出Set-Cookie的内容,遍历key=value的 Cookie 内容,推入一个数组 Neri,同时去除path=|domain=|samesite=|max-age=这几个不需要用的字段(不去除也可以,不影响)
  • 去除本地存储内的Cookie字符串,定义一个Cookie对象,将;号隔开的Cookie字符串分割成元素key=value的数组并将keyvalue一一放入本地Cookie对象中(这一步是为了用新的Cookie中的somekey=somevalue覆盖本地的旧Cookiesomekey=somevalue
  • 遍历新的Cookie数组,key=value=号分割成keyvalue,设置 Cookie 对象中的key为这个新的value,这一步会覆盖相同的keyvalue,达到更新Cookie的效果
  • 遍历Cookie对象,存储成一个key=value,多个key=value;号隔开,得到最后所需的Cookie字符串,并存入本地Storage,在下一次请求时,则从本地Storage中读取这个Cookie字符串带入到header中进行请求

完结,撒花

微信小程序中cookie的使用

https://lynan.cn/mini-program-cookie-util/

Author

Lynan

Posted on

2020-10-19

Licensed under