You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中如何正确拆分含多个Cookie的Set-Cookie头?

问题描述

我遇到的问题和某Stack Exchange问题一致,但我使用React Native,通过Axios拦截器获取Set-Cookie头并存储到本地,代码如下:

cAxios.interceptors.response.use(
  async function (response) {
    const cookieHeaders = response.headers['set-cookie']
    await storeData('cookie', cookieHeaders)
    // 其他代码...
    return response
  },
  function (error) {
    // 错误处理代码...
  }
);

这导致我无法使用原问题中的Headers构造函数方案。目前我拿到的Cookie字符串格式如下:

cookie1=value, cookie2=value2; Expires=Thu, 06 Jul 2023 14:45:25 GMT; path=value5, express-token=value; path=value

如果直接用string.split(', ')拆分,会得到4个错误片段:

  1. cookie1=value
  2. cookie2=value2; Expires=Thu
  3. 06 Jul 2023 14:45:25 GMT; path=value5
  4. express-token=value; path=value

而我需要的正确拆分结果是:

  1. cookie1=value
  2. cookie2=value2; Expires=Thu, 06 Jul 2023 14:45:25 GMT; path=value5
  3. express-token=value; path=value

请问有没有办法正确解析这个字符串,得到正确的Cookie值?

解决方案

方法1:正则拆分(简洁高效)

利用正则的正向预查,只在", "后面紧跟合法Cookie键([a-zA-Z0-9-_]+=格式)时进行拆分,避开Expires字段里的逗号:

const cookieStr = "cookie1=value, cookie2=value2; Expires=Thu, 06 Jul 2023 14:45:25 GMT; path=value5, express-token=value; path=value";
const cookies = cookieStr.split(/, (?=[a-zA-Z0-9-_]+=)/);
console.log(cookies);

该正则的逻辑是:匹配, ,但要求后续必须是Cookie键的起始(字母/数字/下划线/短横线 + =),这样就能精准拆分不同的Cookie项。

方法2:手动遍历解析(更稳妥)

如果担心正则存在边界情况,可以手动遍历字符串,通过标记是否处于Expires字段内来决定是否拆分:

function parseCookieString(cookieStr) {
  const cookies = [];
  let current = '';
  let inExpires = false;

  for (let i = 0; i < cookieStr.length; i++) {
    const char = cookieStr[i];
    // 遇到", "且不在Expires字段中时,保存当前Cookie并重置
    if (char === ',' && cookieStr[i+1] === ' ') {
      if (!inExpires) {
        cookies.push(current.trim());
        current = '';
        i++; // 跳过空格
        continue;
      }
    }
    // 标记是否进入Expires字段
    if (current.includes('Expires=')) {
      inExpires = true;
      // 遇到"; "时,说明Expires字段结束,取消标记
      if (char === ';' && cookieStr[i+1] === ' ') {
        inExpires = false;
      }
    }
    current += char;
  }
  // 加入最后一个Cookie项
  if (current) cookies.push(current.trim());
  return cookies;
}

// 使用示例
const cookieStr = "cookie1=value, cookie2=value2; Expires=Thu, 06 Jul 2023 14:45:25 GMT; path=value5, express-token=value; path=value";
console.log(parseCookieString(cookieStr));

可选:解析Cookie详细属性

拆分完成后,还可以进一步解析每个Cookie的键值对和属性(如Expires、path等):

// 解析单个Cookie的详细信息
function parseSingleCookie(cookieItem) {
  const parts = cookieItem.split(';').map(p => p.trim());
  const [keyValue] = parts;
  const [key, value] = keyValue.split('=');
  const attributes = {};
  for (let i = 1; i < parts.length; i++) {
    const [attrKey, attrValue] = parts[i].split('=');
    attributes[attrKey.toLowerCase()] = attrValue || true;
  }
  return { key, value, attributes };
}

// 批量解析所有Cookie
const parsedCookies = cookies.map(parseSingleCookie);

内容的提问来源于stack exchange,提问作者Dylan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 01:44:59