自定义封装微信小程序request请求

// 自定义网络请求方法

var common = {}
var baseUrl = ""   //默认请求地址前缀

/*
  url 请求地址
  param 请求参数
  callFun 请求成功回调
  that 防止页面this指向问题
  errCallBack 请求失败回调
  hideLoading 是否隐藏加载弹框 默认展示
  methods 设置请求方式Get请求或是Post请求
*/

common.post = function(url, param, callFun, that, errCallBack, hideLoading,methods) {

	if (!hideLoading) {
		wx.showToast({
			title: '加载中',
			icon: 'loading',
			mask:true,
			duration:500
		})
	}
	
	let postUrl = baseUrl + url
	
	if(param){
		if(methods && methods=="Get"){
			if (typeof param == 'object') {
				for (let key in param) {
					postUrl += '&' + key + '=' + param[key];
				};
				param = null;
			}
		}
	}else if(!param){
		param = {}
	}
	
	return new Promise((resolve, reject) => {
		wx.request({
			url: postUrl,
			method: methods || 'Post',
			data: param || {},
			success: res => {
				resolve(res)
				if(typeof callFun==='function'){
					callFun(res.data)
				}else if(typeof that[callFun]==='function'){
					that[callFun](res.data)
				}else if(typeof that[callFun]==='undefined'){
					console.log("未定义方法:"+callFun)
				}
				if (!hideLoading) {
					wx.hideToast()
				}
			},
			fail: err => {
				reject(err)
				if (errCallBack) {
					if(typeof(errCallBack)==='function'){
						errCallBack(err)
					}else if(typeof that[errCallBack] === 'function'){
						that[errCallBack](err)
					}else if(typeof that[errCallBack] === 'undefined'){
						// console.error('未定义方法:'+errCallBack)
					}
				}
				if (!hideLoading) {
					wx.hideToast()
				}
			}
		});
	}).then((res)=>{
		console.log(postUrl,res.data)  //打印接口数据方便调试
	}).catch((err)=>{
		console.log("请求接口出错",err)
	})

}

common.get = function(url, param, callFun, that, errCallBack, hideLoading) {
  common.post(url, param, callFun, that, errCallBack, hideLoading,'Get')
}

module.exports = common

使用时先在页面引入该js,然后在需要的时候调用,例如:


var common=require('../../utils/common.js')


Page({

/**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
	  let that=this
	  common.post("a.php",{name:'abc',id:1},'resData',that,'errData')
  },
  
  resData(res){
	  console.log(res)
  },

})

注: 根据实际情况修改使用!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值