微信小程序網絡請求封裝

請求報文示例 請求報文示例json

// request.js  https://XXXXXXXX/XXX/yy/yyy
var API_URL = 'https://XXXXXXXX/XXX/'
function request(method, requestHandler) {
    var api_key = 'XXX'   //用於加密的key
    var APPEND_URL = requestHandler.url
    var tradeId = requestHandler.tradeId
    // 獲取當前時間戳
    var timestamp = getDate(new Date)
    var param = {
        "head": {
            "timestamp": timestamp,
            "tradeId": tradeId,
            "validCode": "",
            // "userId" : wx.getStorageSync('userId'),
            // "token" : wx.getStorageSync('token')
        },
        "body": {
        }
    }
    //封裝head節dian
    var head_dic = param.head
     var plainStr
     if( wx.getStorageSync('userId') != null ||  wx.getStorageSync('token')!= null) {
        head_dic.userId = wx.getStorageSync('userId')
        head_dic.token = wx.getStorageSync('token')
       plainStr = head_dic.tradeId + head_dic.timestamp +head_dic.userId+head_dic.token+api_key
    } else {
    plainStr = head_dic.tradeId + head_dic.timestamp +api_key
    }
    var validCode1 = utilMd5.hexMD5(plainStr)  // md5加密
    var validCode = validCode1.toUpperCase()
    head_dic.validCode = validCode
    param.head = head_dic
    param.body =  requestHandler.params
    
    wx.request({
        url: API_URL + APPEND_URL+'.json',
        data: { param: JSON.stringify(param) },   //json轉son字符串
        method: method, // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
        header: {
            'content-Type': 'application/x-www-form-urlencoded'
        }, // 設置請求的 header

        success: function (res) {
            //注意:能夠對參數解密等處理
            requestHandler.success(res)
        },
        fail: function () {
            requestHandler.fail()
        },
        complete: function () {
            // complete
        }
    })
}

var requestHandler = {
    url: '',
    tradeId:'',
    params: {},
    success: function (res) {
        // success
    },
    fail: function () {
        // fail
    },
}

// GET
function GET(requestHandler) {
    request('GET', requestHandler)
}

// POST
function POST(requestHandler) {
    request('POST', requestHandler)
}
module.exports = {
    GET: GET,
    POST: POST,
    showToast: showToast
}

調用api

createShopRequest: function () {
    var that = this
    var params = new Object()
    params.shopName = ''
 
    requestServer.POST(
      {
        url: 'yy/yyy',
        tradeId: 'yyy',
        params: params,
        success: function (res) {
          console.log(res.data)
        },
        fail: function () {
        },
      })
  },
相關文章
相關標籤/搜索