request.js 2.7 KB

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