斷斷續(xù)續(xù)的我又回來了,雖然沒幾個(gè)人看,但是呢自己總要有點(diǎn)儀式感。主要是最近又寫了一個(gè)小程序,發(fā)現(xiàn)寫完 vue 回頭寫微信小程序 簡直順暢的不得了,比我直接用 Android 切過去可真的好太多了。OK,廢話停止,正文開始...
前提:
已在 微信公眾平臺(tái) ==》開發(fā) ==》 開發(fā)管理 ==》 服務(wù)器域名 request合法域名 中配置請(qǐng)求的基礎(chǔ)域名。還有 uploadFile合法域名、socket合法域名 等,按照需求配置相關(guān)域名即可。多個(gè)域名用 ;(英文;) 隔開即可。
例如:請(qǐng)求的路徑為 https://www.baidu.com/api,只需配置 https://www.baidu.com
準(zhǔn)備:
首先 了解清楚以下:
請(qǐng)求url: 微信小程序中唯一必填字段,
請(qǐng)求方式 :一般是 GET/POST,微信小程序默認(rèn)GET
請(qǐng)求頭:
content-type :請(qǐng)求的參數(shù)格式,微信小程序默認(rèn) ‘a(chǎn)pplication/json’,常用的還有 "application/x-www-form-urlencoded" ,
Accept:接收的數(shù)據(jù)格式, 一般為'application/json'
請(qǐng)求參數(shù):根據(jù)請(qǐng)求頭設(shè)置的參數(shù)格式寫對(duì)應(yīng)的參數(shù)即可,如果沒有則不寫
對(duì)于請(qǐng)求參數(shù)不理解的 可以看 ??HTTP請(qǐng)求中的參數(shù)提交 && GET和POST兩種基本請(qǐng)求方法的區(qū)別
) ??
開始使用:
相關(guān) API 使用的聚合數(shù)據(jù) 免費(fèi)API, 需要可自己注冊(cè)賬號(hào)獲取即可 https://www.juhe.cn
let city = '上海';
let key = '6483ffe27e1425d240365e190a7993dc';
wx.request({
url:'https://apis.juhe.cn/simpleWeather/query?city='+city+'&key='+key,
method:'GET',//請(qǐng)求方式
header:{
'content-type': 'application/x-www-form-urlencoded'//請(qǐng)求頭 根據(jù)項(xiàng)目配置
},
success(res){
console.log('success =====',res)
},
fail(res){
console.log('fail =====',res)
},
complete(res){
console.log('complete =====',res)
}
})
var params = {
city: '上海',
key: '6483ffe27e1425d240365e190a7993dc' }
wx.request({
url: 'https://apis.juhe.cn/simpleWeather/query',
method:'POST',//請(qǐng)求方式
data:params,//參數(shù)
header:{
'content-type': 'application/x-www-form-urlencoded'//請(qǐng)求頭 根據(jù)項(xiàng)目配置
},
success(res){
console.log('success =====',res)
},
fail(res){
console.log('fail =====',res)
},
complete(res){
console.log('complete =====',res)
}
})
無論使用哪種方式都可以請(qǐng)求到數(shù)據(jù):

只要和確定好請(qǐng)求參數(shù),請(qǐng)求頭,請(qǐng)求方式,就可以正常獲取到數(shù)據(jù)。
BUT 網(wǎng)絡(luò)請(qǐng)求是異步的,也就是你不能把獲取到的數(shù)據(jù) return 給調(diào)用者,需要通過回調(diào)把數(shù)據(jù)傳回給調(diào)用者。(PS:如果你非要每次請(qǐng)求都單獨(dú)寫一個(gè)請(qǐng)求方法,完全可以在異步回調(diào)中直接處理,但是 應(yīng)該沒有這樣的吧 會(huì)把自己累死的)
封裝:
1、封裝網(wǎng)絡(luò)請(qǐng)求,要清楚哪些是可變的,哪些是不變的。
通常來說 header 不會(huì)每次都變,當(dāng)然 也有可能會(huì)變化 (萬一后臺(tái)就是玩呢,同一個(gè)項(xiàng)目不同的請(qǐng)求非要搞不同的 header 呢 ,嗯 前端的脾氣就是這樣被磨沒的。所以針對(duì)這種情況也寫好,整的死死的,來啥樣的 照收不誤。但是代碼還是要盡量保持整潔 畢竟維護(hù)的還是我們自己),參數(shù)/請(qǐng)求地址url/請(qǐng)求方法,肯定是會(huì)變的。
2、對(duì)請(qǐng)求結(jié)果的處理
通常會(huì)把成功獲取數(shù)據(jù)的交給調(diào)用者自己處理,如果失敗 還是統(tǒng)一處理比較好,畢竟每次調(diào)用都處理失敗 也是挺多冗余代碼的。
var defaultHeader = {
'Accept': 'application/json',
'content-type': 'application/x-www-form-urlencoded',
}
request:function(url,method,header,data,successCB,failCB){
wx.showLoading({
title: '加載中...',
mask:true
})
wx.request({
url: rootUrl + url,
method:method,
data:data?data:'',
header:header?header: defaultHeader,
success(res){
if(res.statusCode==200){
// 處理數(shù)據(jù) 不需要返回所有數(shù)據(jù)
if(successCB && typeof successCB == "function"){
successCB(res.data)
}
}else{
// 服務(wù)器錯(cuò)誤 此時(shí)給出提示 且 不允許用戶下一步操作
wx.showModal({
title:'溫馨提示',
content:'出錯(cuò)了,請(qǐng)稍后重試',
showCancel:false,
})
}
},
fail(res){
// 提示報(bào)錯(cuò)信息
wx.showModal({
showCancel: false,
content: res.errMsg
});
// 調(diào)用者處理,也可不處理
if(failCB && typeof failCB == "function"){
failCB(res)
}
},
complete(res){
// 無論成功失敗 加載結(jié)束 加載框消失
wx.hideLoading({
complete: (res) => {
// 這里處理下 否則真機(jī)會(huì)報(bào)錯(cuò)
//in promise) MiniProgramError {"errMsg":"hideLoading:fail:toast can't be found"}
console.log('hideLoading',res)
},
})
}
})
}
主要的請(qǐng)求寫好了,這樣的話這個(gè)請(qǐng)求方法的參數(shù)也太多了,所以,多寫個(gè)方法簡化下
get:function(url,data, successCB, failCB){
return request(url,data,'GET',data, successCB, failCB)
},
post:function(url,data, successCB, failCB){
return request(url,data,'POST',data, successCB, failCB)
},
調(diào)用
// =========GET============
let city = '上海';
let key = '6483ffe27e1425d240365e190a7993dc';
this.get('simpleWeather/query?city='+city+'&key='+key,null,function(res){
console.log('success===',res)
}, function(err){
console.log('fail===', err)
});
// =========POST============
let param = {
city:'上海',
key:'6483ffe27e1425d240365e190a7993dc'
}
this.post('simpleWeather/query',param,function(res){
console.log('success===',res)
}, function(err){
console.log('fail===', err)
});
使用Promise封裝:
Promise 解決異步回調(diào)嵌套問題
使用 Promise 最大的好處就是可以 鏈?zhǔn)秸{(diào)用! && 回調(diào)方法! 鏈?zhǔn)秸{(diào)用讓代碼簡潔、易讀,尤其是代碼的請(qǐng)求存在前后關(guān)系的時(shí)候,
promiseRequest:function(url,data,method,header){
var defaultHeader = {
'Accept': 'application/json',
'content-type': 'application/x-www-form-urlencoded',
}
return new Promise(function(resolve,reject){
wx.request({
url: rootUrl + url,
method: method,
data: data ? data : '',
header: header?header:defaultHeader,
success(res) {
if (res.statusCode == 200) {
// 處理數(shù)據(jù) 不需要返回所有數(shù)據(jù)
resolve(res.data)
} else {
// 服務(wù)器錯(cuò)誤 此時(shí)給出提示 且 不允許用戶下一步操作
wx.showModal({
title: '溫馨提示',
content: '出錯(cuò)了,請(qǐng)稍后重試',
showCancel: false,
})
}
},
fail(res) {
// 提示報(bào)錯(cuò)信息
wx.showModal({
showCancel: false,
content: res.errMsg
});
let errorMsg = errorMsg(res)
reject(errorMsg)
},
complete(res) {
// 無論成功失敗 加載結(jié)束 加載框消失
wx.hideLoading({
complete: (res) => {
// 這里處理下 否則真機(jī)會(huì)報(bào)錯(cuò)
//in promise) MiniProgramError {"errMsg":"hideLoading:fail:toast can't be found"}
console.log('hideLoading', res)
},
})
}
})
})
},
可以看到 和封裝前最大的區(qū)別就是 成功和失敗的回調(diào)。
繼續(xù)寫一層方便調(diào)用
get:function(url,data){
return this.promiseRequest(url,data,'GET',null)
},
post:function(url,data){
return this.promiseRequest(url,data,'POST',null)
},
調(diào)用
get('simpleWeather/query?city='+city+'&key='+key,null).then(res=>{
console.log('success get===',res)
}).catch(error=>{
console.log('error get===',error)
})
let param = {
city:'上海',
key:'6483ffe27e1425d240365e190a7993dc'
}
post('simpleWeather/query',param).then(res=>{
console.log('success get===',res)
}).catch(error=>{
console.log('error get===',error)
})
至此 已完成微信小程序網(wǎng)絡(luò)請(qǐng)求的基本使用和封裝。
但是 其實(shí)還有一個(gè)隱藏的小問題,通常一個(gè)頁面會(huì)調(diào)用多個(gè)接口,在第一個(gè)接口返回服務(wù)器問題的時(shí)候,應(yīng)該取消其他的網(wǎng)絡(luò)請(qǐng)求,目前還沒找到解決方案,希望了解的朋友可以說下,先謝了????
最后慣例給自己一句話:
好好地生活和工作很重要,但關(guān)照自己的內(nèi)心更重要
如果心太疲憊 不防換個(gè)讓心舒服的環(huán)境