newHttp.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. const {
  2. globalData: {
  3. baseUrl
  4. }
  5. } = getApp();
  6. export class Http {
  7. constructor() {}
  8. request({
  9. url,
  10. data = {},
  11. method = 'GET',
  12. header,
  13. callback = '',
  14. responseType,
  15. loadingTips = 'Loading...',
  16. } = {}) {
  17. let _this = this;
  18. uni.showLoading({
  19. title: loadingTips,
  20. // mask: mask ? mask : false
  21. });
  22. // mask ? uni.showNavigationBarLoading() : '';
  23. const apiList = ['/customer/account/customerWechartLog', '/basic/area/selectByInternational',
  24. '/customer/account/getLoginVerifyCodeImg', '/customer/account/apply/getApplyVerifCode', '/customer/account/apply/addApply'
  25. ];
  26. const index = apiList.indexOf(url);
  27. const token = index > -1 ? '' : uni.getStorageSync('token');
  28. const locale = uni.getStorageSync('locale') || 'zh_CN';
  29. return new Promise((resolve, reject) => {
  30. uni.request({
  31. url: `${baseUrl}${url}`,
  32. data,
  33. method,
  34. header: {
  35. 'Content-Type': 'application/json',
  36. Authorization: token ? 'bearer ' + token : '',
  37. 'Accept-Language': locale,
  38. 'portalType': 2
  39. },
  40. callback,
  41. responseType,
  42. success: (res) => {
  43. let statusCode = res.statusCode;
  44. let resData = res.data;
  45. if (callback) return callback(resData.data);
  46. if (statusCode == 200) {
  47. // 如果请求返回的是文件流,需要单独处理
  48. if (responseType == 'arraybuffer') {
  49. resolve(resData);
  50. return;
  51. }
  52. if (resData.code === '0000') {
  53. resolve(resData.data);
  54. } else {
  55. reject(resData, statusCode)
  56. }
  57. } else if (statusCode == 404) {
  58. console.log('接口不存在');
  59. } else if (statusCode == 401) {
  60. uni.reLaunch({
  61. url: '/pages/login/login'
  62. });
  63. } else {
  64. uni.showModal({
  65. title: '提示',
  66. content: res.data.message,
  67. showCancel: false,
  68. confirmText: '确认'
  69. });
  70. reject(resData, statusCode)
  71. }
  72. },
  73. fail: (err) => {
  74. console.log('fail', err);
  75. uni.showModal({
  76. title: '提示',
  77. content: `Network request failed`,
  78. showCancel: false,
  79. confirmText: '确认'
  80. });
  81. },
  82. complete: function(res) {
  83. uni.hideLoading && uni.hideLoading();
  84. uni.hideNavigationBarLoading() && uni.hideNavigationBarLoading();
  85. }
  86. })
  87. })
  88. }
  89. }