JS正則表達式解析 Set-Cookie 響應頭

最近有同事用小程序接入我的服務端登錄,不巧微信小程序不認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);


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章