request.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. var _debug = false;
  2. var host = _debug ? 'https://test.toktok.beer/' : 'https://app.toktok.beer/';
  3. /**
  4. * POST请求
  5. * URL:接口
  6. * postData:参数,json类型
  7. * doSuccess:成功的回调函数
  8. * doFail:失败的回调函数
  9. */
  10. function postData(url, parmas, success, fail) {
  11. let token = wx.getStorageSync('Auth-Token') || '';
  12. let header = {
  13. 'content-type': 'application/x-www-form-urlencoded',
  14. 'Auth-User-Agent': 'WechatApplet#WeChat#unknown#WeChat#100',
  15. 'Auth-Token': token
  16. }
  17. for (var key in parmas) {
  18. if(parmas[key] == null) {
  19. delete parmas[key];
  20. }
  21. }
  22. wx.request({
  23. //项目的真正接口,通过字符串拼接方式实现
  24. url: host + url,
  25. header: header,
  26. data: parmas,
  27. method: 'POST',
  28. success(res) {
  29. _debug ? console.log(res) : '';
  30. if(res.data.code==200) {
  31. success(res)
  32. }else if(res.data.code==401 || res.data.code==402) {
  33. wx.redirectTo({
  34. url: '../login/login'
  35. })
  36. }else{
  37. wx.showToast({
  38. title: res.data.msg,
  39. icon: 'none',
  40. duration: 2000
  41. })
  42. }
  43. },
  44. fail(res) {
  45. console.log(res)
  46. }
  47. })
  48. }
  49. //GET请求,不需传参,直接URL调用,
  50. function getData(url, parmas, success) {
  51. let token = wx.getStorageSync('Auth-Token') || '';
  52. let header = {
  53. 'content-type': 'application/x-www-form-urlencoded',
  54. 'Auth-User-Agent': 'WechatApplet#WeChat#unknown#WeChat#100',
  55. 'Auth-Token': token
  56. }
  57. for (var key in parmas) {
  58. if(parmas[key] == null) {
  59. delete parmas[key];
  60. }
  61. }
  62. wx.request({
  63. url: host + url,
  64. header: header,
  65. data: parmas,
  66. method: 'GET',
  67. success(res) {
  68. _debug ? console.log(res) : '';
  69. if(res.data.code==200) {
  70. success(res)
  71. }else if(res.data.code==401 || res.data.code==402) {
  72. wx.redirectTo({
  73. url: '../login/login'
  74. })
  75. }else{
  76. wx.showToast({
  77. title: res.data.msg,
  78. icon: 'none',
  79. duration: 2000
  80. })
  81. }
  82. },
  83. fail(res) {
  84. console.log(res)
  85. }
  86. })
  87. }
  88. function getUrlKey (url, name) {
  89. return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(url) || [, ""])[1].replace(/\+/g, '%20')) || null
  90. }
  91. /**
  92. * module.exports用来导出代码
  93. * js文件中通过var call = require("../util/request.js") 加载
  94. * 在引入引入文件的时候" "里面的内容通过../../../这种类型,小程序的编译器会自动提示,因为你可能
  95. * 项目目录不止一级,不同的js文件对应的工具类的位置不一样
  96. */
  97. module.exports = {
  98. _debug: _debug,
  99. host: host,
  100. postData: postData,
  101. getData: getData,
  102. getUrlKey: getUrlKey
  103. }