小程序模板网

微信小程序网络请求封装

请求报文示例 请求报文示例

 

				
  1. // request.js https://XXXXXXXX/XXX/yy/yyy
  2. var API_URL = 'https://XXXXXXXX/XXX/'
  3. function request(method, requestHandler) {
  4. var api_key = 'XXX' //用于加密的key
  5. var APPEND_URL = requestHandler.url
  6. var tradeId = requestHandler.tradeId
  7. // 获取当前时间戳
  8. var timestamp = getDate(new Date)
  9. var param = {
  10. "head": {
  11. "timestamp": timestamp,
  12. "tradeId": tradeId,
  13. "validCode": "",
  14. // "userId" : wx.getStorageSync('userId'),
  15. // "token" : wx.getStorageSync('token')
  16. },
  17. "body": {
  18. }
  19. }
  20. //封装head节dian
  21. var head_dic = param.head
  22. var plainStr
  23. if( wx.getStorageSync('userId') != null || wx.getStorageSync('token')!= null) {
  24. head_dic.userId = wx.getStorageSync('userId')
  25. head_dic.token = wx.getStorageSync('token')
  26. plainStr = head_dic.tradeId + head_dic.timestamp +head_dic.userId+head_dic.token+api_key
  27. } else {
  28. plainStr = head_dic.tradeId + head_dic.timestamp +api_key
  29. }
  30. var validCode1 = utilMd5.hexMD5(plainStr) // md5加密
  31. var validCode = validCode1.toUpperCase()
  32. head_dic.validCode = validCode
  33. param.head = head_dic
  34. param.body = requestHandler.params
  35.  
  36. wx.request({
  37. url: API_URL + APPEND_URL+'.json',
  38. data: { param: JSON.stringify(param) }, //json转son字符串
  39. method: method, // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
  40. header: {
  41. 'content-Type': 'application/x-www-form-urlencoded'
  42. }, // 设置请求的 header
  43.  
  44. success: function (res) {
  45. //注意:可以对参数解密等处理
  46. requestHandler.success(res)
  47. },
  48. fail: function () {
  49. requestHandler.fail()
  50. },
  51. complete: function () {
  52. // complete
  53. }
  54. })
  55. }
  56.  
  57. var requestHandler = {
  58. url: '',
  59. tradeId:'',
  60. params: {},
  61. success: function (res) {
  62. // success
  63. },
  64. fail: function () {
  65. // fail
  66. },
  67. }
  68.  
  69. // GET
  70. function GET(requestHandler) {
  71. request('GET', requestHandler)
  72. }
  73.  
  74. // POST
  75. function POST(requestHandler) {
  76. request('POST', requestHandler)
  77. }
  78. module.exports = {
  79. GET: GET,
  80. POST: POST,
  81. showToast: showToast
  82. }

调用

 

				
  1. createShopRequest: function () {
  2. var that = this
  3. var params = new Object()
  4. params.shopName = ''
  5.  
  6. requestServer.POST(
  7. {
  8. url: 'yy/yyy',
  9. tradeId: 'yyy',
  10. params: params,
  11. success: function (res) {
  12. console.log(res.data)
  13. },
  14. fail: function () {
  15. },
  16. })
  17. },


易优小程序(企业版)+灵活api+前后代码开源 码云仓库:starfork
本文地址:https://www.eyoucms.com/wxmini/doc/course/23747.html 复制链接 如需定制请联系易优客服咨询:800182392 点击咨询
QQ在线咨询