微信小程序中使用 内嵌 H5 时,登录问题的处理方法

时间:2024-01-30 22:45:52

在微信小程序的开发中,经常遇到需要使用 <web-view></web-view> 内嵌 H5 的需求。在这种需求中比较棘手的问题应该就是登录状态的判断了,小程序中的登录状态怎样与H5中的登录状态保持一致?

一般来说,后端开发同事多数会要求我们在 H5 中的接口请求中携带 cookie,来获取用户当前的登录状态。这个该如何实现呢?

分为以下几步:

1、小程序中,封装统一的接口请求方法(以便在每个接口中都携带 cookie,放在 header 中);

const request = parameter => {
    //url必填项
    if (!parameter || parameter == {} || !parameter.url) {
        console.log(\'Data request can not be executed without URL.\');
        return false;
    } else {
        var murl = parameter.url;
        var headerCookie = wx.getStorageSync(\'cookie\');
        //判断是否有独自cookie请求
        var selfCookie = parameter.selfCookie;
        selfCookie && (headerCookie += selfCookie);
        wx.request({
            url: murl,
            data: parameter.data || {},
            header: {
                // \'Content-Type\': \'application/x-www-form-urlencoded\',
                \'Cookie\': headerCookie
            },
            method: parameter.method || \'POST\',
            success: function(res) {
                parameter.success && parameter.success(res);

            },
            fail: function(e) {
                parameter.fail && parameter.fail(e);
                // console.log(e.errMsg);
                wx.showToast({
                    title: \'网络信号较差\',
                    icon: \'loading\',
                    duration: 3000
                });
            },
            complete: function() {
                parameter.complete && parameter.complete();
            }
        });
    }

}

 

2、小程序中,当用户成功登录之后,保存当前cookie;

utils.request({
  url: url,
   data: {},
   success: (res) => {
     wx.setStorageSync(\'cookie\', res.header["Set-Cookie"]);
   }
});

3、在<web-view></web-view> 内嵌 H5 的页面,获取已保存的 cookie 值,使用 url 拼接的方式传给 H5 页面;

// <web-view> 页面模板
<view> <web-view src="{{url}}" ></web-view> </view>

//cookie 处理

  let value = wx.getStorageSync(\'cookie\'),cookie_vl;

  if (value) {
    cookie_vl= value.match(new RegExp("(^| )"+"jxi-m-sid"+"=([^;]*)(;|$)"))[2] ;
  }

  // 处理 url,拼接 cookie 值

  this.setData({
    url: `${this.data.url}?${cookie_vl}`
  });

4、在H5中的处理方法是: 获取 cookie 值并写入。

let cookie = window.location.href.split(\'?\')[1];

document.cookie = `jxi-m-sid=${cookie};domain=${host};path=/`;

上述代码中的 host 值得是 H5 链接中的域名。

这样处理之后,接口发送请求时会携带该 cookie,后端同事获取之后就可以判断登录状态了。