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

页面刷新后如何持久化登录状态?LocalStorage存储仍失效

页面刷新后登录状态无法持久化问题求助

各位开发者好,我正面临页面刷新后状态无法持久化的问题。目前已将登录状态存入LocalStorage,但每次刷新页面后用户都会退出登录,尝试多种方案均未解决,恳请各位提供帮助,谢谢。

Core.ts 代码

class Core {
  agv: typeof agv;
  auth: Auth;
  workflow: WorkflowApi;
  graphql: GraphQLSdk;
  fleetState: Stream<FleetState>;
  taskList: Stream<TaskList>;
  zoneList: Stream<ZoneList>;

  configuration = getConfiguration();

  url: string;

  constructor(options: Options) {
    const auth = getAuth(options);
    const graphqlUrl = `${options.host}/graphql`;
    const graphql = getSdk(new GraphQLClient(graphqlUrl, { fetch: authMiddleware({ auth, fetch: options.fetch }) }));

    const streamContext = {
      ...options,
      headers: getAuthHeaders(auth),
      getSites: () => auth.session.value?.sites || [],
    };

    this.auth = auth;
    this.workflow = getWorkflowApi({ auth }) ;
    this.graphql = graphql;
    this.fleetState = fleetState.call({
      ...options,
      headers: getAuthHeaders(auth),
      getSites: () => auth.session.value?.sites || [],
    });

    this.configuration.map.fetch = this.configuration.map.fetch.bind(async () => {
      const site = auth.session.value.sites[0];
      return graphql.map({ site }).then(({ map }) => map);
    });

    this.taskList = taskList.call(streamContext);
    this.zoneList = zoneList.call(streamContext);

    this.agv = {
      ...agv,
      graphql,
      map: this.configuration.map,
      getSites: () => auth.session.value?.sites || [],
    } as typeof agv;

    auth.session.listen(session => {
      window.localStorage.setItem('session', JSON.stringify(session));
      console.log(session);
      if (session) {
        this.configuration.map.fetch();
      }
    });
  }
}

export { Core };

问题分析与解决方案

问题根源

目前代码只实现了登录状态变更时写入LocalStorage,但页面刷新后Core重新实例化时,auth对象是全新创建的,没有从LocalStorage读取并恢复之前保存的session数据,导致auth.session初始为空,触发退出登录状态。

修复步骤

  1. 初始化时恢复LocalStorage中的session
    在创建auth实例后,立即读取LocalStorage并注入到auth.session中:

    constructor(options: Options) {
      // 先读取本地存储的session
      const savedSession = window.localStorage.getItem('session');
      const initialSession = savedSession ? JSON.parse(savedSession) : null;
    
      const auth = getAuth(options);
      // 恢复session到auth实例(根据你的Stream实现调整赋值方式)
      if (initialSession) {
        auth.session.value = initialSession;
      }
    
      // 后续原有代码...
    }
    

    如果getAuth支持传入初始session参数,也可以直接在调用时传入:

    const savedSession = window.localStorage.getItem('session');
    const initialSession = savedSession ? JSON.parse(savedSession) : null;
    const auth = getAuth({ ...options, initialSession });
    
  2. 验证认证中间件的有效性
    确保authMiddleware和getAuthHeaders会实时读取auth.session.value,而不是仅在初始化时获取一次。如果中间件是静态初始化的,需要调整为动态读取当前session,避免恢复session后接口请求仍无认证信息。

  3. 校验session有效性
    恢复session前建议检查是否过期(如果session包含过期时间字段),避免注入无效session导致接口请求失败:

    if (savedSession) {
      const parsedSession = JSON.parse(savedSession);
      // 假设session有expires字段
      if (parsedSession.expires && Date.now() < parsedSession.expires) {
        auth.session.value = parsedSession;
      } else {
        // 清除过期session
        window.localStorage.removeItem('session');
      }
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 02:05:19