微信小程序 网络请求封装

网络封装公共类 netUtil.js

 function request(method,obj){
   const app=getApp();
   var header =obj.header || {};
   if (!header['content-type']) {
     header['content-type'] = 'application/json'
   }
  wx.request({
    url:obj.url,
    data:obj.data,
    method:method,
    header:header,
    success:function(res){
      app.dlog('success'+obj.data._gp+obj.data._mt+res); //log日志
      wx.hideLoading();
      if(res.data){
        if (res.data != undefined && res.data != null) {
          if (res.data.errmsg == "成功" && res.data.errno == 200) {
            typeof obj.success == "function" && obj.success(res.data.data);
          } else if (res.data.errno == 10001){
            app.globalData.LoginType = -1
            showToast('当前用户未登录')//这部分是对所有接口公共的错误指令进行处理
          }else{
            typeof obj.fail == "function" && obj.fail(res);//这里直接把返回的所有内容回传,是为了对不同的errno进行不同处理
          }
        }
      } else {
        app.dlog('success' + obj.data._gp + obj.data._mt + res);
      } 
    },
    fail: function(error) {
      wx.hideLoading();
      app.dlog('error' + obj.data._gp + obj.data._mt + error);
      typeof obj.fail == "function" && obj.fail('加载失败');
    }
  })
},
function showToast(str, icon) {
  wx.showToast({
    title: str,
    duration: 1500,
    icon: icon == 'undefined' || icon == null || icon == '' ? 'none' : icon
  })
}

//封装wx.showLoading
function showLoading(title, mask) {
  wx.showLoading({
    title: title,
    mask: mask == 'undefined' || mask == null || mask == '' ? false : mask
  })
}
/**
 * 供外部post请求调用
 */
function post(obj) {
  request("POST", obj);
}

/**
 * 供外部get请求调用
 */
function get(obj) {
  request("GET", obj);
}
/** 注册 对外开放 */
module.exports = {
  postRequest: post,
  getRequest: get,
  showToast: showToast,
  showLoading: showLoading
}

调用方法:

import netUtil from '../netUtil.js';//首先引入方法文件
loadData:function(e){
  var that = this
   var param = {}
   param._gp = 'user.user'//接口大类
   param._mt = 'getUser'//具体方法
   param.userId = app.globalData.USERID
   app.dlog(param)
   netUtil.showLoading('加载中...')
   netUtil.getRequest({
      url: app.globalData.URL,
      data: param,
      header: {
        'content-type': 'application/json',
        'accessToken': app.globalData.TOKEN
      },
      success: function(res) {
        //对返回的数据进行处理
      },
      fail: function(res) {
        //对报错信息进行判断 提示处理
      }
    })
}

你可能感兴趣的:(微信小程序 网络请求封装)