微信小程序封裝http訪問網絡庫實例代碼
發表時(shí)間:2021-5-11
發布人(rén):融晨科技
浏覽次數:87
之(zhī)前都是(shì)使用LeanCloud爲(wéi / wèi)存儲,現在(zài)用傳統API調用時(shí)做如下封裝
var HOST = 'http://localhost/lendoo/public/index.php/';
// 網站請求接口,統一爲(wéi / wèi)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);
}
})
}
// 導出(chū)模塊
module.exports = { post: post
}
然後前端調用就(jiù)可以(yǐ)這(zhè)樣做了(le/liǎ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
});
}
});
一般對自己寫的(de)接口給自己用的(de)時(shí)候,method方法或header都是(shì)約定好的(de),所以(yǐ)不(bù)用重複書寫。
1 header: {
2 "content-type": "application/x-www-form-urlencoded"
3 },
4 method: 'POST'
而(ér)fail回調方法也(yě)可以(yǐ)統一處理;進一步地(dì / de),也(yě)可以(yǐ)對success回調裏的(de)針對code值進一步判斷,特定錯誤碼統一處理,比如跳轉登錄頁面等。