微信小程序封裝http訪問網絡庫實例代碼
之前都是使用LeanCloud為存儲,現在用傳統API調用時做如下封裝
文檔出處:https://mp.weixin.qq.com/debug/wxadoc/dev/api/network-request.html
代碼如下:
var HOST = 'http://localhost/lendoo/public/index.php/';// 網站請求接口,統一為postfunction 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值進一步判斷,特定錯誤碼統一處理,比如跳轉登錄頁面等。
經過上述處理,是不是變得簡潔了?
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答