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

如何将登录获取的JWT token存入localStorage的userInfo中?

解决方法

你只需要在获取到接口返回的token后,将token和需要存储的用户信息合并为新对象,再写入localStorage即可,修改后的参考代码如下:

export const login = (userID, password) => async (dispatch) => {
    try {
        dispatch({ type: USER_LOGIN_REQUEST });
       
        const url = "http://localhost:8080/authenticate/";
        const config = {
          auth: {
            username: userID,
            password,
          },
        };
    
        const data = {};
        const response = await axios.post(
            url, 
            data, 
            config,
        )
        
        if (response.status === 200 && response.data.token) {
          // 登录成功且获取到有效token
          const token = response.data.token;
          console.log("TOKEN\n" + token);
          // 构造要存储的userInfo对象,不需要存密码可以删除password字段
          const userInfo = {
            userID: userID,
            password: password,
            token: token
          }
          // 同时更新redux状态和localStorage
          dispatch({ type: USER_LOGIN_SUCCESS, payload: userInfo});
          localStorage.setItem("userInfo", JSON.stringify(userInfo) );
        }
      } catch (error) {
        dispatch({
            type: USER_LOGIN_FAIL,
            payload:
                error.response && error.response.data.ErrorMessage
                    ? error.response.data.ErrorMessage
                    : error.message,
        });
      }
};

注意事项

  • 不要将明文密码存入localStorage,浏览器本地存储为明文可读,遭遇XSS攻击时会直接泄露用户账号信息,常规场景仅存储用户ID和token即可
  • 新增了token存在性判断,避免接口异常返回空值时存入无效数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 08:45:02