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

localStorage中token获取失败:getSuppliers()返回null的解决方法

解决方案

根据你的localStorage存储状态(截图显示键为status,对应值是包含authorisation.token的JSON字符串),你之前的所有尝试都错误地用嵌套路径作为key去取值,这不符合localStorage的键值对存储规则。

正确的getToken()实现如下:

getToken() {
    // 先获取status对应的JSON字符串
    const statusString = localStorage.getItem('status');
    if (!statusString) return null;
    
    try {
        // 解析为JS对象
        const status = JSON.parse(statusString);
        // 逐层安全获取token,避免属性不存在时报错
        return status?.authorisation?.token || null;
    } catch (e) {
        console.error('解析status失败:', e);
        return null;
    }
}

为什么之前的方法都无效?

  • 最初用localStorage.getItem('status.authorisation.token'):localStorage的key是独立字符串,不存在嵌套key的写法,因此无法获取到值。
  • 尝试authorisation.token或token作为key:你的localStorage中根本没有这两个键,自然返回null。
  • 部分写法未使用JSON.parse:即使键名正确,不解析的话拿到的是原始字符串,无法读取嵌套的token属性。

额外说明

加入try-catch是为了防止status的值不是合法JSON字符串导致报错;使用可选链操作符?.可以避免某一层属性不存在时抛出Cannot read property 'xxx' of undefined的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 15:27:21