网友真实露脸自拍10p,成人国产精品秘?久久久按摩,国产精品久久久久久无码不卡,成人免费区一区二区三区

小程序模板網

微信小程序封裝wx.request

發布時間:2021-06-03 10:39 所屬欄目:小程序開發教程
在小程序開發中,通過接口獲取后臺數據,這時候我們不得不在每個頁面的js文件中寫到:wx.request({

url:'',.....}) 但是調用很多接口的時候,會非常頻繁的使用request,作為一名php開發人員,顯然我們需要對他進行一下封裝:

1.在utils同級目錄下建立service



2.typeof cb == "function" && cb(res.data) 我的理解是

利用的&&的運算規律,首先判斷cb是不是一個方法, 這里的==可以作為類型是否相當的判斷,然后在&&中如果前面的不滿足,

后面的則不會執行;如果是cb是一個方法,調用cb方法,并且傳入success成功回調的userinfo參數

并且return 的是回調函數,而不是具體的數據

var rootDocment = 'https://xxxxxxxxxxxxx/';
var header = {
  'Accept': 'application/json',
  'content-type': 'application/json',
  'Authorization': null,
}
function getReq(url, cb) {
  wx.showLoading({
    title: '加載中',
  })
  console.log("header=="),
    console.log(header)
  wx.request({
    url: rootDocment + url,
    method: 'get',
    header: header,
    success: function (res) {
      wx.hideLoading();
      return typeof cb == "function" && cb(res.data)
    },
    fail: function () {
      wx.hideLoading();
      wx.showModal({
        title: '網絡錯誤',
        content: '網絡出錯,請刷新重試',
        showCancel: false
      })
      return typeof cb == "function" && cb(false)
    }
  })
}
 
function postReq(url, data, cb) {
  wx.showLoading({
    title: '加載中',
  })
    console.log("header=="),
    console.log(header),
    wx.request({
      url: rootDocment + url,
      header: header,
      data: data,
      method: 'post',
      success: function (res) {
        wx.hideLoading();
        return typeof cb == "function" && cb(res.data)
      },
      fail: function () {
        wx.hideLoading();
        wx.showModal({
          title: '網絡錯誤',
          content: '網絡出錯,請刷新重試',
          showCancel: false
        })
        return typeof cb == "function" && cb(false)
      }
    })
 
}
module.exports = {
  getReq: getReq,
  postReq: postReq,
  header: header,
}  
header 中的一些數據可能是需要在app.js中登錄后返回的Token,這時候我們需要在app.js中

var http = require('service/http.js')

http.header.Authorization = 'Bearer '+res.data;//給header 賦值

// 將方法暴露出去

getReq: http.getReq,

postReq: http.postReq,


使用:

    http.getReq("item/getshopbanner/"+getApp().globalData.shopIdx,function(res){
                      console.log("banner==")
                      console.log(res)
                    })


易優小程序(企業版)+靈活api+前后代碼開源 碼云倉庫:starfork
本文地址:http://www.xiuhaier.com/wxmini/doc/course/26048.html 復制鏈接 如需定制請聯系易優客服咨詢:800182392 點擊咨詢
QQ在線咨詢
AI智能客服 ×