request封裝可以方便我們統(tǒng)一管理請求函數(shù),減少冗余代碼。
const baseUrl = "xxx"; //請求根
const http = ({
url = "",
param = {},
type = 'from',
...other
} = {}) => {
wx.showLoading({ //可以不加
title: '請求中...'
})
let timeStart = Date.now();
return new Promise((resolve, reject) => {
wx.request({
url: baseUrl + url,
data: param,
header: { //兩種 ,一種json 一種 from
'content-type': type == 'from' ? 'application/x-www-form-urlencoded' : 'application/json'
},
...other,
complete: res => {
wx.hideLoading(); //同上 ,可以不加
console.log(`耗時(shí)${Date.now() - timeStart}`);
if (res.statusCode >= 200 && res.statusCode < 300) {
resolve(res.data);
... //此處根據(jù)自己的業(yè)務(wù)需求自行定義
} else {
reject(res)
}
}
})
})
}
使用實(shí)例
// 1.無需傳參數(shù)請求(默認(rèn)get請求,header為from)
const a = () => {
return http({
url: 'xxx',
})
}
// 2.帶參數(shù)請求并且為post
const b = param => {
return http({
url: 'xxx',
method: 'post'
})
}
// 3.帶參數(shù)請求post,header為json
const c = param => {
return http({
url: 'xxx',
type: 'json',
method: 'post'
})
}
module.exports = {
a,
b,
c,
}
頁面中使用
const api = require(xxxx); //找到我們封裝的api
requestA() {
api.a().then(res=> {
console.log(res);
}) .catch(err =>{
console.log(err);
})
},
requestB() {
let data = {}
api.b(data).then(res => {}).catch(err=>{})
}
//如果頁面有多個請求同時(shí)進(jìn)行,可以這樣寫
Promise.all([
api.a,
api.b,
]).then(res =>{}).catch(err=>{})
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。