微信小程序wx.request获取response header

网络请求中,有时我们需要根据response header中的一些信息来进行一些判断或者操作,在小程序中要如何实现呢?
RequestTask = wx.request(Object object) 可以通过RequestTask对象来实现。
注意:基础库 1.4.0 开始支持,低版本需做兼容处理。

RequestTask.abort()
中断请求任务

RequestTask.onHeadersReceived(function callback)
监听 HTTP Response Header 事件。会比请求完成事件更早

RequestTask.offHeadersReceived(function callback)
取消监听 HTTP Response Header 事件

   const requestTask = wx.request({
          url: url,
          method: method,
          data: data,
          header: header,
          dataType: dataType,
          success: function(res) {
            isOutTime = false;
            if (res.statusCode != 200) {
              res = (typeof res == "string") ? JSON.parse(res) : res;
              typeof(fcb) == "function" && fcb(res);
              return;
            }
            let data = (typeof res.data == "string") ? JSON.parse(res.data) : res.data;
            typeof(scb) == "function" && scb(data || {});
          },
          fail: function(res) {
            res = (typeof res == "string") ? JSON.parse(res) : res;
            typeof(fcb) == "function" && fcb(res);
          },
          complete: function() {
            if (isOutTime) {
              wx.showToast({
                title: '请求超时',
                icon: 'loading',
                duration: 2000
              })
              if (url.indexOf('/notAuth/') < 0 || url.indexOf('/servlet/StaffServlet') < 0) {
                // wx.clearStorageSync("username");
              }else{
                var i = setInterval(
                  function() {
                    wx.reLaunch({
                      url: '/pages/login/login',
                    })
                    clearInterval(i);
                  }, 2000);
              }
              console.log("请求超时:"+url)
            }
            isOutTime = false;
            if (!o.hidetoast) {
              that.loading._hide();
            }
            typeof(ccb) == "function" && ccb();
          }
        });
        requestTask.onHeadersReceived((res) => {
          console.log(url)
          console.log(“获取到了header”);
          if (res.header && res.header["Set-Cookie"]) {
            if (url.indexOf('/notAuth/') > -1 || url.indexOf('/servlet/StaffServlet') > -1) {
              console.log("session keep")
            } else {
              console.log("session失效")
              wx.showToast({
                title: 'session失效',
                icon: 'loading',
                duration: 2000
              })
              requestTask.abort();
              var i = setInterval(
                function() {
                  wx.reLaunch({
                    url: '/pages/login/login',
                  })
                  clearInterval(i);
                }, 2000);
            }
          }
        })

以上是我项目中封装的hhtp请求的统一方法,在每次发起网络请求时,当发现请求超时及服务器重启导致session失效的情况,就自动返回登录页。

猜你喜欢

转载自blog.csdn.net/qq_29712053/article/details/90080051