緣起
之前都是使用LeanCloud為存儲,現(xiàn)在用傳統(tǒng)API調(diào)用時做如下封裝
文檔出處:https://mp.weixin.qq.com/debug/wxadoc/dev/api/network-request.html
代碼如下:
var HOST = 'http://localhost/lendoo/public/index.php/';
// 網(wǎng)站請求接口惦积,統(tǒng)一為post
function post(req) {
//發(fā)起網(wǎng)絡(luò)請求
wx.request({
url: HOST + req.uri,
data: req.param,
header: {
"content-type": "application/x-www-form-urlencoded"
},
method: 'POST',
success: function (res) {
req.success(res.data)
},
fail: function (res) {
console.log(res);
}
})
}
// 導(dǎo)出模塊
module.exports = {
post: post
}
然后前端調(diào)用就可以這樣做了:
var http = require('../../utils/http.js');
...
http.post({
uri: http.orderListUri,
param: {
third_session: wx.getStorageSync('third_session')
},
success: function (data) {
that.setData({
orderList: data
});
}
});
一般對自己寫的接口給自己用的時候钦讳,method方法或header都是約定好的持搜,所以不用重復(fù)書寫嫌蚤。
header: {
"content-type": "application/x-www-form-urlencoded"
},
method: 'POST'
而fail回調(diào)方法也可以統(tǒng)一處理锐帜;進一步地被济,也可以對success回調(diào)里的針對code值進一步判斷,特定錯誤碼統(tǒng)一處理贴妻,比如跳轉(zhuǎn)登錄頁面等切油。
經(jīng)過上述處理,是不是變得簡潔了名惩?