在app.js中 添加自定义post方法
//app.js
App({
//other code...
/**
* 自定义get, post函数,返回Promise
* +-------------------
* @param {String} url 接口网址
* @param {arrayObject} data 要传的数组对象 例如: {name: 'zhangsan', age: 32}
* +-------------------
* @return {Promise} promise 返回promise供后续操作
*/
appRequest : function(method, url, data){
var promise = new Promise((resolve, reject) => {
//init
var that = this;
//网络请求
wx.request({
url: url,
data: data,
method: method,
header: {
'content-type': methods == 'GET' ? 'application/json' : 'application/x-www-form-urlencoded',
},
dataType: 'json',
success: function (res) {//服务器返回数据
if (res.data.status == 1) {//res.data 为 后台返回数据,格式为{"data":{...}, "info":"成功", "status":1}, 后台规定:如果status为1,既是正确结果。可以根据自己业务逻辑来设定判断条件
resolve( res.data.data );
} else {//返回错误提示信息
reject( res.data.info );
}
},
error: function (e) {
reject('网络出错');
}
})
});
return promise;
},
//other codes...
)}
其他页面调用app.js的 post()函数
const app = getApp();
//获取首页传参的广告aid
page({
//other code...
//页面第一次加载
onLoad: function () {
var data = {id: 18};//要传的数组对象
wx.showLoading({
title: '加载中...',
})
//调用 app.js里的 post()方法
app.appRequest('http://接口网址', data).then( (res)=>{
console.log(res);//正确返回结果
wx.hideLoading();
} ).catch( (errMsg)=>{
console.log(errMsg);//错误提示信息
wx.hideLoading();
} );
},
//other code...
})
网友评论