2021-08-17根据Java返回数据做自动登录

根据Java返回数据做自动登录

需求

A端带参访问某一Java接口后跳转B端(中途自动登录),接口返回B端URL

实现思路

Java侧返回URL中带有用户ID或其他身份标识,B端在created之前处理URL并登录

访问Java接口数据
{
    "user_id": "1",
    "user_name": "admin",
    "user_phone": "18812340001"
}

接口返回数据
{
    "code": 200,
    "msg": "SUCCESS",
    "url": "http://localhost:8080/#/?userId=3"
}

/**
* 整个地址流转过程:
* @param 访问地址 http://localhost:8080/#/?userId=3
*  1、将访问地址存入 LocalStorage
*  2、将访问地址剪切为不带userId的地址,页面地址栏地址为(http://localhost:8080/#/)
*  3、页面刷新时将 LocalStorage 中存入的 访问地址取出,做刷新使用
*  4、页面刷新时,重复 步骤 1
*/
  /**
   * VUE生命周期,挂载之前
   */
  beforeCreate() {
    // 判断当前地址是否为带有 userId的地址,主要用于页面刷新时的地址变更
    // 当页面刷新时,地址为不带userId的地址,会造成登录失败,页面会一直刷新
    if(document.URL.indexOf('?') == -1) {
      let currentUrl = getLocalStorage('userId');
      // 所以将 LocalStorage 中的原地址(带有userId的地址)取出做为刷新后的地址
      window.location.href = currentUrl.currentUrl;
    }
  },
  created() {
    this.getUserId();
    // (方法省略)
    this.login();
  },
  /**
   * VUE生命周期,挂载完成
   */
  mounted() {
    // 将接口返回的地址存入 LocalStorage
    setLocalStorage({'userId': window.location.href});
    // 将当前地址剪切为不带userId的地址
    window.location.href = document.URL.substring(0, document.URL.indexOf('?'));
  },
  /**
   * 从地址中截取用户ID,做无感知登录使用
   */
  getUserId() {
      // 当前地址:http://localhost:8080/#/?userId=3
      let currentUrl = document.URL;
      // 截取ID http://localhost:8080/#/?userId=3  3
      let userId = currentUrl.substring(currentUrl.indexOf('=') + 1);
      // 登录账号的ID(省略)
      this.account = userId;
    },
    /**
     * 登录
     */
    async login() {
      // 获取用户ID
      this.getUserId();
      // 当用户ID 为空时,再次获取
      if (!this.account) {
        this.getUserId();
        // 再次获取为空则返回,防止页面无限刷新
        if (!this.account) {
          return;
        }
      }
      await authLoginByAccount({ userId: this.account })
        .then(res => {
          console.log('res--->', res)
          // 登录后逻辑省略
          // ...
         });
       }).catch(error => {
          Toast.fail(error.data.errmsg);
        });
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值