在app.js中 添加自定義post方法
//app.js
App({
//other code...
/**
* 自定義get, post函數(shù)惯豆,返回Promise
* +-------------------
* @param {String} url 接口網(wǎng)址
* @param {String} method 接口類型
* @param {arrayObject} data 要傳的數(shù)組對(duì)象 例如: {name: 'zhangsan', age: 32}
* +-------------------
* @return {Promise} 返回promise對(duì)象供后續(xù)操作
*/
appRequest: function(url, method, data){
let promise = new Promise((resolve, reject) => {
//網(wǎng)絡(luò)請(qǐng)求
wx.request({
url,
data,
method,
header: {
"content-type": method.toUpperCase() == "GET" ? "application/json" : "application/x-www-form-urlencoded",
},
dataType: "json",
success: function (res) {
//服務(wù)器返回?cái)?shù)據(jù)
console.log(res);
//res.data 為 后臺(tái)返回?cái)?shù)據(jù)池磁,格式為{"data":{...}, "info":"成功", "status":1}, 后臺(tái)規(guī)定:如果status為1,既是正確結(jié)果】蓿可以根據(jù)自己業(yè)務(wù)邏輯來(lái)設(shè)定判斷條件
if (res.data.errmsg == "ok") {
resolve(res.data);
} else {
//返回錯(cuò)誤提示信息
reject(res.data.info);
}
},
error: function (e) {
reject('網(wǎng)絡(luò)出錯(cuò)', e);
}
})
});
return promise;
},
//other codes...
)}
其他頁(yè)面調(diào)用app.js的 post()函數(shù)
const app = getApp();
//獲取首頁(yè)傳參的廣告aid
page({
//other code...
//頁(yè)面第一次加載
onLoad: function () {
var data = {id: 18};//要傳的數(shù)組對(duì)象
wx.showLoading({
title: '加載中...',
})
//調(diào)用 app.js里的 post()方法
app.appRequest('http://接口網(wǎng)址', 'post', data).then( (res)=>{
console.log(res);//正確返回結(jié)果
wx.hideLoading();
} ).catch( (errMsg)=>{
console.log(errMsg);//錯(cuò)誤提示信息
wx.hideLoading();
} );
},
//other code...
})