封装微信小程序wx.request

封装微信小程序wx.request()

  • 在utils文件夹下新建文件request.js
/**
 * 封装小程序内置 wx.request
 */
 function getServerData(url,parmadata,loadingflag,method,timeout,header){ //请求地址,参数,是否显示等待框,请求类型,超时时间,请求头
  if(loadingflag){
    wx.showLoading({
      title:"加载中"
    });
  }
  return new Promise((resolve,reject)=>{
    wx.request({
      data:parmadata,
      method:method,
      timeout:timeout || 30000, 
      url: url,
      header:header,
      success(res){
        console.log(res);
        resolve(res);
        if(loadingflag){
          wx.hideLoading();
        }
      },
      fail:function(err){
        console.error(err);
        reject(err);
        if(loadingflag){
          wx.hideLoading();
        }
        wx.showToast({
          title: '接口异常!',
        })
      }
    });
  }) 
 }
module.exports = {  //暴漏出去  getRequest为自定义名字 return中的getServerData 为上面封装的方法名
  getRequest:function(url,parmadata,loadingflag,method,timeout,header){
    return getServerData(url,parmadata,loadingflag,method,timeout,header)
  }
}
  •  调用 首先进行引入
const utilRequest = require("../../../utils/request");
 let that = this;
 let url = App.globalData.url + '/userdevice/getUserDevices';
 let data={
   user_uuid:wx.getStorageSync('uuid')
 }
 //getRequest(url,data,true) 即为调用
 utilRequest.getRequest(url,data,true).then((res)=>{
     
   console.log(res);//res就是返回值
      
 });

猜你喜欢

转载自blog.csdn.net/qq_38880700/article/details/105557016