微信小程序 wx.request统一调用

2018-03-18  本文已影响290人  阿昕_

起因

在小程序里发起网络请求的时候需要写很多的参数,当频繁调用时,每次都写真心觉得累,那就封个方法统一调用吧

官方文档

wx.request({
  url: 'test.php', //仅为示例,并非真实的接口地址
  data: {
     x: '' ,
     y: ''
  },
  header: {
      'content-type': 'application/json' // 默认值
  },
  success: function(res) {
    console.log(res.data)
  }
})

函数

var _config = {
  serverUrl: 'https://xxxx.com/'
}

function testFun(paraData, cb){
  requestApi('testFun', { test: paraData.test }, cb)
}

module.exports = {
  testFun
}
//调用API 统一方法
function requestApi(ApiName, PostData, cb) {
  wx.request({
    url: _config.serverUrl + ApiName,
    data: PostData,
    method: 'POST',
    success: function (res) {
      typeof cb == "function" && cb(null, res)
    },
    fail: function () {
      typeof cb == "function" && cb(res)
    }
  })
}
//获取应用实例
var util = require('../../utils/util.js')
util.testFun({ test: testData.test }, function (err, res) {
});

总结

统一调用不仅减少了代码量,而且有利于维护与管理,团队合作的时候也能让别人快速了解你的代码,而不是像在看一锅粥一样。

上一篇 下一篇

猜你喜欢

热点阅读