1. 首先在公共的app.js(或公共JS文件)中加入如下方法:
App({
// post请求封装
post: function(url, data) {
var promise = new Promise((resolve, reject) => {
var that = this
var postData = data
wx.request({
url: url,
data: postData,
method: 'POST',
header: { 'content-type': 'application/x-www-form-urlencoded' },
success: function(res) {
//服务器返回数据
if (res.data.ret === 'OK') {//根据数据返回格式来判断
resolve(res)//根据数据格式需求返回
} else {
//返回错误提示信息
reject(res.data.msg)
}
},
fail: function(e) {
reject('网络出错')
}
})
})
return promise
},
//get请求
get:function(url,data){
var promise = new Promise((reslove,reject)=>{
var that = this
var getData = data
wx.request({
url:url,
data:getData,
method:'GET',
header:{'content-type': 'application/x-www-form-urlencoded' },
sucess:function(res){
if (res.data.ret ==='OK') {
reslove(res)
} else {
reject(res.data.msg)
}
},
fail:{
function(e){
reject('网络出错')
}
}
})
})
return promise
}
})
2.其他页面调用app.post()函数
const app = getApp();
Page({
onLoad:function(){
//post请求
app.post(api,data)
.then(res => {
console.log(res) //正确返回结果
wx.hideLoading()
})
.catch(errMsg => {
console.log(123) //错误提示信息
wx.hideLoading()
})
}
})