Wepy封裝wx.request


import wepy from 'wepy'
/**wx.request服務封裝 */
export class RequestService {
/**
* create by wq
* info 錯誤信息
* callBack 回調函數
* errTip 自定義錯誤信息
*/
static httpHandlerError(info, callBack, errTip) {
wepy.hideLoading()
/**請求成功,退出該函數 */
if ((info.statusCode >= 200 && info.statusCode <= 207) || info.statusCode === 304) {
return false
} else {
/**401 沒有權限時,重新登錄 */
if (info.statusCode === 401) {
wepy.redirectTo({
url: 'index'
})
}
/**判斷是否有自定義錯誤信息,如果有,優先使用自定義錯誤信息,其次曝出後臺返回錯誤信息 */
let errorInfo = ''
if (errTip) {
errorInfo = errTip
} else {
if (info.data.message) {
errorInfo = info.data.message
} else {
errorInfo = '也許服務器忙!'
}
}
wepy.showToast({
title: errorInfo,
icon: 'loading',
duration: 3000
})
/**發生錯誤信息時,如果有回調函數,則執行回調 */
if (callBack) {
callBack()
}
return true
}
}
/**
* create by wq
*請求封裝
*method 請求方式
*reqData 發送請求數據
*reqUrl 請求路徑
*failFn 請求失敗,執行該函數
*sucFn 請求成功,執行該函數
*/
static soeRequest(method, reqData, reqUrl, failFn, sucFn) {
wepy.request({
/**header 如果需要驗證token 可封裝另外的getHeaders函數獲取本地緩存token */
// header: this.getHeaders(),
header: {
'content-type': 'application/json'
},
data: reqData,
url: reqUrl,
method: method,
complete: (res) => {
let error = this.httpHandlerError(res, failFn)
if (error) return;
sucFn(res);
}
})
}
}
//在index.wpy頁面中, 需要發送請求, < script > 標籤頭部引入
import { RequestService } from '../Request’;
// 使用函數調用接口示例:
RequestService.soeRequest('GET', '', url,
(fail) => {
console.log(fail);
console.log('失敗');
},
(res) => {
console.log(res);
console.log('成功');
})



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章