如何在JavaScript中解析Cookie

2022-06-15大约3分钟

在浏览器中,Cookie是以包含键值对的字符串格式存储。那么,如何解析浏览器Cookie字符串并返回所有cookie键值对的对象?

方式1:自己写代码来解析

自己用代码解析的话,要考虑这几点:

  1. ;为分隔符,将每个键值对分开;
  2. =为分隔符,将每个键和值分开;
  3. 对于键和值,用decodeURIComponent()来解码。

具体代码:

const parseCookie = (value) =>
  value
  .split(';')
  .map(v => v.split('='))
  .reduce((acc, v) => {
    acc[decodeURIComponent(v[0].trim())] = decodeURIComponent(v[1].trim());
    return acc;
  }, {});
  
parseCookie('support_es6=1; name=lema.fun');
//输出: {support_es6: '1', name: 'lema.fun'}

方式2: 使用开源的npm包。

这里推荐一个包:cookie,使用很广泛。

const cookie = require('cookie');
const cookies = cookie.parse('support_es6=1; name=lema.fun');
//输出: {support_es6: '1', name: 'lema.fun'}

一般情况下,建议使用现成的包,而不是自己写代码来实现。