Cookie中JSON格式异常问题
嘿,这个问题我之前也踩过坑!Cookie本身对存储的字符有严格限制,JSON里的双引号、斜杠这些特殊字符,直接存进去很容易在传输过程中被自动转义,导致客户端拿到的JSON格式乱掉。咱们一步步来解决:
服务器端的正确处理姿势
你得确保把JSON数据先序列化,再做URL编码,之后再塞到Cookie里,不能直接把序列化后的字符串丢进去。Express里可以这么写:
// 准备要存在Cookie里的JSON数据 const userData = { id: 123, username: "testUser", isAdmin: false }; // 先序列化为JSON字符串,再做URL编码 const encodedCookieValue = encodeURIComponent(JSON.stringify(userData)); // 设置Cookie,按需配置参数 res.cookie('userInfo', encodedCookieValue, { httpOnly: false, // 如果你需要客户端JS读取,这里要设为false,生产环境建议开启httpOnly secure: process.env.NODE_ENV === 'production', // 生产环境开启HTTPS时设为true maxAge: 24 * 60 * 60 * 1000 // 有效期设为1天 });
客户端的正确解析方法
客户端拿到Cookie后,得先把值做URL解码,再解析成JSON对象,不然直接解析肯定会报错:
// 先整个工具函数方便获取指定Cookie function getCookie(cookieName) { const cookieStr = `; ${document.cookie}`; const cookieParts = cookieStr.split(`; ${cookieName}=`); if (cookieParts.length === 2) return cookieParts.pop().split(';').shift(); } // 获取并解析Cookie里的JSON数据 const encodedUserInfo = getCookie('userInfo'); if (encodedUserInfo) { try { const userInfo = JSON.parse(decodeURIComponent(encodedUserInfo)); console.log('正常解析后的JSON:', userInfo); } catch (err) { console.error('JSON解析失败,大概率是编码/解码没做好:', err); } }
为啥会出现格式异常?
举个直观的例子:如果服务器直接把JSON.stringify(userData)的结果(比如{"id":123,"username":"testUser"})存进Cookie,浏览器会自动把双引号转义成\",客户端拿到的就变成了"{\"id\":123,\"username\":\"testUser\"}"——外层多了一层不必要的引号,内部转义也乱了,这时候直接JSON.parse肯定会失败。
另外提个小提醒:单条Cookie的存储上限是4KB,如果你的JSON数据太大,建议换个方式存,比如localStorage,或者用JWT存在Cookie里(JWT本身就是经过编码的字符串,适配Cookie存储)。
内容的提问来源于stack exchange,提问作者이상원




