httpService.js 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import { TokenStorage } from "../utils/storageSevice.js";
  2. import { API_URL, UPLOAD_URL, ISDEBUG } from "../utils/globalConstant.js";
  3. import {common} from "../utils/common.js";
  4. import { CACHE} from "../utils/cache.js";
  5. //统一请求的http服务
  6. function HttpService(url, param, completeCallback){
  7. let token = TokenStorage.getData();
  8. param['accessToken']=token?token:'';
  9. let promise = new Promise((resolve, reject)=> {
  10. const requestTask = wx.request({
  11. url: API_URL+url,
  12. method: 'POST',
  13. data:param,
  14. header: {
  15. 'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
  16. },
  17. success: function (res) {
  18. if (ISDEBUG) console.log("请求地址为:" + API_URL + url)
  19. if (ISDEBUG) console.log("请求参数为:" + JSON.stringify(param))
  20. if (ISDEBUG) console.log("请求回来的数据:");
  21. if (ISDEBUG) console.log(res);
  22. if (res.statusCode == 401 && res.data == "没有登录"){
  23. wx.showModal({
  24. title: '提示',
  25. content: '访问服务器失败',
  26. showCancel: false
  27. })
  28. return;
  29. }
  30. resolve(res.data);
  31. },
  32. fail: function (err) {//失败回调
  33. if (ISDEBUG) console.log("请求失败的地址:" + API_URL + url );
  34. if (ISDEBUG) console.log("失败后的信息:" + err);
  35. reject(err);
  36. },
  37. complete: function (res) {//接口调用结束的回调函数(调用成功、失败都会执行)
  38. completeCallback && completeCallback();
  39. }
  40. })
  41. })
  42. return promise;
  43. }
  44. function HttpUploadService(url, param, filePath, fileName, completeCallback) {
  45. let token = TokenStorage.getData();
  46. param['accessToken'] = token ? token : '';
  47. let promise = new Promise((resolve, reject) => {
  48. const uploadReqTask = wx.uploadFile({
  49. url: UPLOAD_URL + url,
  50. filePath: filePath,
  51. name: fileName,
  52. method: 'POST',
  53. formData: param,
  54. header: {
  55. "Content-Type": "multipart/form-data"
  56. },
  57. success: function (res) {
  58. if (ISDEBUG) console.log("请求地址为:" + UPLOAD_URL + url)
  59. if (ISDEBUG) console.log("请求参数为:" + JSON.stringify(param))
  60. if (ISDEBUG) console.log("请求回来的数据:");
  61. if (ISDEBUG) console.log(res);
  62. if (res.statusCode == 401 && res.data == "没有登录") {
  63. wx.showModal({
  64. title: '提示',
  65. content: '上传失败',
  66. showCancel: false
  67. })
  68. return;
  69. }
  70. resolve(JSON.parse(res.data))
  71. },
  72. fail: function (err) {//失败回调
  73. if (ISDEBUG) console.log("请求失败的地址:" + UPLOAD_URL + url);
  74. if (ISDEBUG) console.log("失败后的信息:" + err);
  75. reject(err);
  76. },
  77. complete: function (res) {//接口调用结束的回调函数(调用成功、失败都会执行)
  78. completeCallback && completeCallback();
  79. }
  80. })
  81. })
  82. return promise;
  83. }
  84. module.exports = {
  85. HttpService: HttpService,
  86. HttpUploadService: HttpUploadService
  87. }