JS正则表达式解析 Set-Cookie 响应头
程序员文章站
2022-07-13 11:59:53
...
最近有同事用小程序接入我的服务端登录,不巧微信小程序不认Set-Cookie,必须手动解析,几个小时百度无果,逼出自己重新手写一个,代码见如下。
function ParseSetCookie(a) {
var arr = a.replace(/expires=(.*?)GMT/g,function($1) {
return "expires=" + new Date($1).getTime();
}).split(", ");
var cookies = [];
for(var i=0;i<arr.length;i++)
{
let cookie = parse(/([^=;\s]+)=([^;]+);?/g, arr[i].replace(/; httponly/g, "$&=true"));
cookies.push(cookie);
}
function parse(reg, text) {
if (!reg || !text) return {}
const hash = {};
let res = reg.exec(text);
while (res !== null) {
hash[res[1]] = res[2];
res = reg.exec(text);
}
return hash;
}
return cookies;
}
使用方法如下:
var cookiestr="demo_token=pq9Qqy1XVc-HQ==; expires=Thu, 05 Dec 2019 01:42:53 GMT; path=/; httponly, demo_SESS=f1f1EJ0MG_IU4_jwGLmRqe23sB0BJeWpMY171V0PaCgKnkPW8YIiZ-ILg8XBLvjq; path=/; expires=Thu, 05 Dec 2019 01:42:53 GMT; httponly";
var result=ParseSetCookie(cookiestr);
//输出是一个数组,里面有你想要的
console.log(result);