微信小程式wx.request()封裝
阿新 • • 發佈:2018-12-18
微信小程式開發過程中,請求用的次數是比較多的,那麼能自己每次的重複程式碼太多,所以還是自己封裝一個請求吧,使程式碼越來越精簡。
現在請求分為兩種一種是GET一種是POST,在微信小程式的請求中POST請求的header中的'content-type'為'application/x-www-form-urlencoded',就需要做一些區分
引數詳解:
url | 請求的地址 |
method | 請求方式GET或POST |
data | 請求引數 示例{'name':'張三'} |
callBack | 回撥函式 |
說明:以下程式碼中的code具體以服務端返回的為準
// 公用網路請求 commonRequest: function(url, method, data, callBack){ //method GET或POST var that = this, IP = that.globalData.IP, content_type = 'application/json', accessToken = wx.getStorageSync('accessToken'), longitude = wx.getStorageSync('longitude'), //經度 latitude = wx.getStorageSync('latitude'), //緯度 commParam = { 'longitude': longitude, 'latitude': latitude }, //公共引數 commParam = JSON.stringify(commParam); //公共引數轉字串 if (method == 'POST'){ content_type = 'application/x-www-form-urlencoded' } wx.request({ url: IP + url, data: data, method: method, header: { 'content-type': content_type, 'accessToken': accessToken, 'commParam': commParam }, success: function (res){ // console.log(res.data) if(res.data.code == '200'){ callBack({ status: '200', hasData: true, datainfo: res.data.datas }) } else if (res.data.code == '404'){ //列表資料為空 callBack({ status: '404', hasData: false, datainfo: '' }) } else if (res.data.code == '504'){ //未登入或登入失效 callBack({ status: '504', hasData: false, datainfo: '' }) }else { wx.showToast({ title: res.data.message, icon: 'none', duration: 2000 }) } }, fail: function (res){ wx.showToast({ title: '請求超時', icon: 'none', duration: 2000 }) } }) }