網絡請求封裝實例
實現定制要求和方便調用,對微信小程序的網絡請求接口進行了封裝
代碼
直接將這個方法放在了app.js中
/** * 接口公共訪問方法 * @param {Object} urlPath 訪問路徑 * @param {Object} params 訪問參數(json格式) * @param {Object} requestCode 訪問碼,返回處理使用 * @param {Object} onSuccess 成功回調 * @param {Object} onErrorBefore 失敗回調 * @param {Object} onComplete 請求完成(不管成功或失敗)回調 * @param {Object} isVerify 是否驗證重復提交 * @param {Object} requestType 請求類型(默認POST) * @param {Object} retry 訪問失敗重新請求次數(默認1次) */ webCall: function (urlPath, params, requestCode, onSuccess, onErrorBefore, onComplete, isVerify, requestType, retry) { var params = arguments[1] ? arguments[1] : {}; //var requestCode = arguments[2] ? arguments[2] : 1; var onSuccess = arguments[3] ? arguments[3] : function () { }; var onErrorBefore = arguments[4] ? arguments[4] : this.onError; var onComplete = arguments[5] ? arguments[5] : this.onComplete; var isVerify = arguments[6] ? arguments[6] : false; var requestType = arguments[7] ? arguments[7] : "POST"; var retry = arguments[8] ? arguments[8] : 1; var that = this; //防止重復提交,相同請求間隔時間不能小于500毫秒 var nowTime = new Date().getTime(); if (this.requestCount[urlPath] && (nowTime - this.requestCount[urlPath]) < 500) { return; } this.requestCount[urlPath] = nowTime; //是否驗證重復提交 if (isVerify) { if (this.verifyCount[urlPath]) { return; } this.verifyCount[urlPath] = true; //重復驗證開關開啟 } console.log("發起網絡請求, 路徑:" + (that.apiHost + urlPath) + ", 參數:" + JSON.stringify(params)); wx.request({ url: that.apiHost + urlPath, data: params, method: requestType, // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT header: { 'content-type': requestType == 'POST' ? 'application/x-www-form-urlencoded' : 'application/json' }, // 設置請求的 header success: function (res) { console.log("返回結果:" + JSON.stringify(res.data)); if (res.data) { if (res.data.statusCode == 200) { //訪問成功 onSuccess(res.data, requestCode); } else if (res.data.statusCode == 300000001) { // 未登錄 that.isLogin = false; onErrorBefore(0, res.data.message, requestCode); } else { onErrorBefore(0, res.data.message == null ? "請求失敗 , 請重試" : res.data.message, requestCode); } } else { onErrorBefore(0, "請求失敗 , 請重試", requestCode); } }, fail: function (res) { retry--; console.log("網絡訪問失敗:" + JSON.stringify(res)); if (retry > 0) return that.webCall(urlPath, params, requestCode, onSuccess, onErrorBefore, onComplete, requestType, retry); }, complete: function (res) { onComplete(requestCode); //請求完成后,2秒后重復驗證的開關關閉 if (isVerify) { setTimeout(function () { that.verifyCount[urlPath] = false; }, 2000); } } }) }
新聞熱點
疑難解答