之前都是使用LeanCloud為存儲,現在用傳統API調用時做如下封裝
文檔出處:https://mp.weixin.qq.com/debug/wxadoc/dev/api/network-request.html
代碼如下:
-
var HOST = 'http://localhost/lendoo/public/index.php/';
-
// 網站請求接口,統一為post
-
-
function post(req) {
-
//發起網絡請求
-
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);
-
}
-
})
-
}
-
// 導出模塊
-
-
module.exports = { post: post
-
}
然后前端調用就可以這樣做了:
-
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都是約定好的,所以不用重復書寫。
-
header: {
-
"content-type": "application/x-www-form-urlencoded"
-
},
-
method: 'POST'
而fail回調方法也可以統一處理;進一步地,也可以對success回調里的針對code值進一步判斷,特定錯誤碼統一處理,比如跳轉登錄頁面等。
經過上述處理,是不是變得簡潔了?
|