在小程序開發中,通過接口獲取后臺數據,這時候我們不得不在每個頁面的js文件中寫到:wx.request({
url:'',.....}) 但是調用很多接口的時候,會非常頻繁的使用request,作為一名php開發人員,顯然我們需要對他進行一下封裝:
1.在utils同級目錄下建立service
2.typeof cb == "function" && cb(res.data) 我的理解是
利用的&&的運算規律,首先判斷cb是不是一個方法, 這里的==可以作為類型是否相當的判斷,然后在&&中如果前面的不滿足,
后面的則不會執行;如果是cb是一個方法,調用cb方法,并且傳入success成功回調的userinfo參數
并且return 的是回調函數,而不是具體的數據
var rootDocment = 'https://xxxxxxxxxxxxx/';
var header = {
'Accept': 'application/json',
'content-type': 'application/json',
'Authorization': null,
}
function getReq(url, cb) {
wx.showLoading({
title: '加載中',
})
console.log("header=="),
console.log(header)
wx.request({
url: rootDocment + url,
method: 'get',
header: header,
success: function (res) {
wx.hideLoading();
return typeof cb == "function" && cb(res.data)
},
fail: function () {
wx.hideLoading();
wx.showModal({
title: '網絡錯誤',
content: '網絡出錯,請刷新重試',
showCancel: false
})
return typeof cb == "function" && cb(false)
}
})
}
function postReq(url, data, cb) {
wx.showLoading({
title: '加載中',
})
console.log("header=="),
console.log(header),
wx.request({
url: rootDocment + url,
header: header,
data: data,
method: 'post',
success: function (res) {
wx.hideLoading();
return typeof cb == "function" && cb(res.data)
},
fail: function () {
wx.hideLoading();
wx.showModal({
title: '網絡錯誤',
content: '網絡出錯,請刷新重試',
showCancel: false
})
return typeof cb == "function" && cb(false)
}
})
}
module.exports = {
getReq: getReq,
postReq: postReq,
header: header,
}
header 中的一些數據可能是需要在app.js中登錄后返回的Token,這時候我們需要在app.js中
var http = require('service/http.js')
http.header.Authorization = 'Bearer '+res.data;//給header 賦值
// 將方法暴露出去
getReq: http.getReq,
postReq: http.postReq,
使用:
http.getReq("item/getshopbanner/"+getApp().globalData.shopIdx,function(res){
console.log("banner==")
console.log(res)
})