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

React useCookie无法存储特殊字符问题求助

React useCookie 无法存储含特殊字符令牌的解决方案

问题原因

Cookie规范里,值不能包含|、空格、逗号、分号这类非URL安全字符,直接存这类字符会导致Cookie值被截断或无法正确写入。你用的令牌132|efsc5d48ffff557f65f8f里的|属于受限字符,所以没法正常存储。

解决方法

存令牌前先用encodeURIComponent做URL编码,读取时再用decodeURIComponent解码还原就行。

修改后的代码示例

const [cookies, setCookie, removeCookie] = useCookies(['cookie-name']);
const authCtx = useContext(authContext);

const onEmailVarification = async () => {
  // const response = userService.emailVarification();
  const _token = "132|efsc5d48ffff557f65f8f";
  // 存储前编码特殊字符
  setCookie('cookie-name', encodeURIComponent(_token), { path: '/' });
}

// 读取令牌时解码
const getToken = () => {
  const encodedToken = cookies['cookie-name'];
  return encodedToken ? decodeURIComponent(encodedToken) : null;
}

额外说明

  • 除了|,@、$、&这类字符也建议编码后再存,避免兼容性问题。
  • 要是用的react-cookie版本较新,部分场景可能自动处理编码,但手动编码能确保所有环境下都正常工作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 16:36:20