用户
 找回密码
 立即注册

QQ登录

只需一步,快速开始

扫一扫,登录网站

小程序社区 首页 教程 实用组件/插件 查看内容

微信小程序网络请求封装

yuzeng84 2017-5-29 00:09

微信小程序网络请求封装

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

  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. wx.request({
  36. url: API_URL + APPEND_URL+'.json',
  37. data: { param: JSON.stringify(param) }, //json转son字符串
  38. method: method, // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
  39. header: {
  40. 'content-Type': 'application/x-www-form-urlencoded'
  41. }, // 设置请求的 header
  42. success: function (res) {
  43. //注意:可以对参数解密等处理
  44. requestHandler.success(res)
  45. },
  46. fail: function () {
  47. requestHandler.fail()
  48. },
  49. complete: function () {
  50. // complete
  51. }
  52. })
  53. }
  54. var requestHandler = {
  55. url: '',
  56. tradeId:'',
  57. params: {},
  58. success: function (res) {
  59. // success
  60. },
  61. fail: function () {
  62. // fail
  63. },
  64. }
  65. // GET
  66. function GET(requestHandler) {
  67. request('GET', requestHandler)
  68. }
  69. // POST
  70. function POST(requestHandler) {
  71. request('POST', requestHandler)
  72. }
  73. module.exports = {
  74. GET: GET,
  75. POST: POST,
  76. showToast: showToast
  77. }

调用

  1. createShopRequest: function () {
  2. var that = this
  3. var params = new Object()
  4. params.shopName = ''
  5. requestServer.POST(
  6. {
  7. url: 'yy/yyy',
  8. tradeId: 'yyy',
  9. params: params,
  10. success: function (res) {
  11. console.log(res.data)
  12. },
  13. fail: function () {
  14. },
  15. })
  16. },
鲜花
鲜花
鸡蛋
鸡蛋
分享至 : QQ空间
收藏
原作者: 大慧慧

相关阅读