您當前位置>首頁 » 新聞資訊 » 小(xiǎo)程序相(xiàng)關 >
微(wēi)信小(xiǎo)程序封裝http訪問(wèn)網絡庫實例代∏← >碼
發表時(shí)間(jiān):2021-5-11
發布人(rén):葵宇科(kē)技(jì)
浏覽次數(shù):87
之前都(dōu)是(shì)使用(yòng)LeanCloud✘§€為(wèi)存儲,現(xiàn)在用(yòng)傳統API調→β''用(yòng)時(shí)做(zuò)如(rú)下(xià)封裝
var HOST = 'http://localhost/lendoo/pu''"blic/index.php/';
// 網站(zhàn)請(qǐng)求接口,統一(yī)為(wèi)post
function post(req) {
//發起網絡請(qǐng)求
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
}
然後前端調用(yòng)就(jiù)可(kě)以這(zhè)樣做(zuò)了(le)♥≥♠:
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
});
}
});
一(yī)般對(duì)自(zì)己寫的(de)接口給自(z>↓÷≥ì)己用(yòng)的(de)時(shí)候,method方法或header都(dōu)≠λα♥是(shì)約定好(hǎo)的(de),所以不(bù)用(yòng)重複書←(shū)寫。
1 header: {
2 "content-type": "application/x-www-form-urlencoded"
3 },
4 method: 'POST'
而fail回調方法也(yě)可(kě)以統一(yī)處理(lǐ);進一(yī)步地(dì→♠$),也(yě)可(kě)以對(duì)success回調裡(lǐ)的(de)針對(duì)®←code值進一(yī)步判斷,特定錯(cuò)誤碼統一(yī)處理(lǐ),比如÷εφ(rú)跳(tiào)轉登錄頁面等。