在app.js中 添加自定义post方法
//app.js
App({
//other code...
/**
* 自定义get, post函数,返回Promise
* +-------------------
* @param {String} url 接口网址
* @param {String} method 接口类型
* @param {arrayObject} data 要传的数组对象 例如: {name: 'zhangsan', age: 32}
* +-------------------
* @return {Promise} 返回promise对象供后续操作
*/
appRequest: function(url, method, data){
let promise = new Promise((resolve, reject) => {
//网络请求
wx.request({
url,
data,
method,
header: {
"content-type": method.toUpperCase() == "GET" ? "application/json" : "application/x-www-form-urlencoded",
},
dataType: "json",
success: function (res) {
//服务器返回数据
console.log(res);
//res.data 为 后台返回数据,格式为{"data":{...}, "info":"成功", "status":1}, 后台规定:如果status为1,既是正确结果。可以根据自己业务逻辑来设定判断条件
if (res.data.errmsg == "ok") {
resolve(res.data);
} else {
//返回错误提示信息
reject(res.data.info);
}
},
error: function (e) {
reject('网络出错', e);
}
})
});
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://接口网址', 'post', data).then( (res)=>{
console.log(res);//正确返回结果
wx.hideLoading();
} ).catch( (errMsg)=>{
console.log(errMsg);//错误提示信息
wx.hideLoading();
} );
},
//other code...
})