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

JSON.parse语法错误排查:Google登录后localStorage数据解析异常

JSON.parse语法错误原因排查及修复

错误根源

localStorage.setItem仅支持存储字符串类型数据,你直接将jwt_decode返回的对象存入localStorage,浏览器会自动把对象转为字符串"[object Object]",这不是合法的JSON格式,导致JSON.parse解析时触发语法错误。

验证方式

打开浏览器控制台执行以下代码,会看到存储的内容是无效字符串:

console.log(localStorage.getItem("user"))

修复方案

1. 修正存储逻辑(登录组件)

将解码后的对象转为JSON字符串再存入:

const responseGoogle = (response) => {
    const decoded = jwt_decode(response.credential);
    localStorage.setItem("user", JSON.stringify(decoded));
};

2. 优化读取逻辑(首页组件)

原代码存在两处问题:判断条件错误(getItem不存在时返回null而非字符串"undefined")、三元分支返回值类型不一致。优化后代码:

// 先获取存储值
const storedUser = localStorage.getItem("user");
// 存在则解析,否则设为默认值(如null或空对象)
const userInfo = storedUser ? JSON.parse(storedUser) : null;

// 若需在无数据时清空localStorage,单独处理
if (!storedUser) {
    localStorage.clear();
}

补充说明

jwt_decode返回的是JavaScript对象,必须通过JSON.stringify转换为JSON字符串,才能被localStorage正确存储和后续解析。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 14:35:24