request.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. var app = getApp();
  2. var requestnum = 0;
  3. const addnum = function(){
  4. if (requestnum==0){
  5. wx.showLoading({
  6. title:"加载中...",
  7. // mask:true
  8. })
  9. }
  10. requestnum++;
  11. }
  12. const reducenum = function(){
  13. requestnum--;
  14. if (requestnum==0){
  15. wx.hideLoading();
  16. }
  17. }
  18. export const get=(url,data,callback,failback)=>{
  19. addnum();
  20. var authorization = wx.getStorageSync("authorization");
  21. wx.request({
  22. url: app.globalData.serverpath+url,
  23. method: "GET",
  24. header: {
  25. "Content-Type": "json",
  26. "Authorization":authorization
  27. },
  28. data:data,
  29. success: function (res){
  30. if(res.statusCode!=200){
  31. if(res.data.message){
  32. wx.showToast({
  33. title:res.data.message,
  34. icon:"none"
  35. })
  36. return;
  37. }
  38. }
  39. callback && callback(res);
  40. },
  41. fail: function (error){
  42. failback && failback(error);
  43. },
  44. complete: function () {
  45. reducenum();
  46. }
  47. })
  48. }
  49. export const post=(url,data,header,callback,failback,noauth)=>{
  50. var authorization = wx.getStorageSync("authorization")
  51. if(typeof header=="function"){
  52. noauth = failback;
  53. failback = callback;
  54. callback = header;
  55. header = {};
  56. }
  57. if(authorization){
  58. addnum();
  59. wx.request({
  60. url: app.globalData.serverpath+url,
  61. method: "POST",
  62. header: Object.assign({
  63. "Content-Type": "application/json",
  64. "Authorization":authorization,
  65. "Accept": "application/vnd.vpgame.v1+json"
  66. },header),
  67. data:data,
  68. success: function (res){
  69. if(res.statusCode!=200){
  70. if(res.data.message){
  71. wx.showToast({
  72. title:res.data.message,
  73. icon:"none"
  74. })
  75. return;
  76. }
  77. }
  78. callback && callback(res);
  79. },
  80. fail: function (error){
  81. failback && failback(error);
  82. },
  83. complete: function () {
  84. reducenum();
  85. }
  86. })
  87. }else{
  88. if(typeof noauth=="function"){
  89. noauth();
  90. }
  91. }
  92. }
  93. export const upload =(url,path,callback)=>{
  94. addnum();
  95. var authorization = wx.getStorageSync("authorization")
  96. wx.uploadFile({
  97. url: app.globalData.serverpath+url, //仅为示例,非真实的接口地址
  98. filePath: path,
  99. name: 'file',
  100. formData:{},
  101. header:{
  102. "Authorization":authorization,
  103. "Accept": "application/vnd.vpgame.v1+json"
  104. },
  105. success: function(res){
  106. callback && callback(res);
  107. },
  108. complete: function () {
  109. reducenum();
  110. }
  111. })
  112. }