小程序wx.request()封装网络请求

1,165 阅读1分钟

wx.request请求封装

_微信提供了api,开发者可以通过wx.request来获取服务器的数据和传递数据。虽然api提供了很大的方便,但是调用多个接口时,代码重复性太高,我们可以进一步封装。
_

wx.request(Object object)

发起 HTTPS 网络请求

参数

示例代码

wx.request({
    url: 'test.php', // 示例接口
    data: {
        x: '',
        y: ''
    },
    header: {
        'content-type': 'application/json' // 默认值
    },
    success(res) {
        console.log(res.data)
    }
})

封装方法一 (结合token实现)

代码目录

在这里插入图片描述

index.js

const apiHttp = "http://192.168.0.105:7001"; // 需要提前知道后端IP地址
const socketHttp = "wss://*****.com/wss";

function request(url, method, data, header) {
  data = data || {};
  header = header || {};
  let token = wx.getStorageSync("token");
  if(token) {
    if(!header || !header["Authorization"]) {
      header["Authorization"] = token;
    }
  }
  wx.showNavigationBarLoading();
  //console.log(apiHttp + url);
  let promise = new Promise(function(resolve, reject) {
    wx.request({
      url: apiHttp + url,
      header: header,
      data: data,
      method: method,
      success: function(res) {
        if(res.statusCode == 401) { //token过期,重新执行登录流程
          reLogin().then(() => {
            resolve();
          }).catch(reason => {
            console.log(reason)
          })
        }
        resolve(res);
      },
      fail: reject,
      complete: function() {
        wx.hideNavigationBarLoading();
      }
    });
  });
  return promise;
}

module.exports = {
  apiHttp: apiHttp,
  socketHttp: socketHttp,
  "get": function(url, data, header) {
    return request(url, "GET", data, header);
  },
  "post": function(url, data, header) {
    return request(url, "POST", data, header);
  },
  "put": function(url, data, header) {
    return request(url, "PUT", data, header);
  },
  "delete": function(url, data, header) {
    return request(url, "DELETE", data, header);
  }
};

PS:补充知识点

封装方法二

代码目录

在这里插入图片描述

request.js

function request(method, url, data, header) {
    return new Promise((resolve, reject) => {
        wx.request({
            url: url,
            data,
            header:header ? header : {'content-type' : 'application/json'},
            method,
            success(res) {
                if(res.data.code) {
                    resolve(res.data)
                }else{
                    wx.showModal({
                        title: '提示',
                        content: res.data.message
                    })
                    resolve(false)
                }
            },
            fail(err) {
                wx.showModal({
                    title: '提示',
                    content: '网络断开,稍后重试!'
                })
                resolve(false)
            }
        })
    })
}

module.exports = {
    "get": function(url, data, header) {
        return request("GET", url, data, header);
    },
    "post": function(url, data, header) {
        return request("POST", url, data, header);
    },
    "put": function(url, data, header) {
        return request("PUT", url, data, header);
    },
    "delete": function(url, data, header) {
        return request("DELETE", url, data, header);
    }
}