http.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import Config from './config.js'
  2. import Util from './util.js'
  3. const app_type = 'pc';
  4. const app_type_name = 'PC';
  5. export default {
  6. sendRequest(params) {
  7. var method = params.method ?? 'POST', // 请求方式
  8. url = Config.baseUrl + params.url, // 请求路径
  9. data = {
  10. app_type,
  11. app_type_name
  12. };
  13. // token
  14. if (uni.getStorageSync('cashier_token')) data.token = uni.getStorageSync('cashier_token');
  15. // siteid
  16. if (uni.getStorageSync('site_id')) data.site_id = uni.getStorageSync('site_id');
  17. //store_id
  18. if (uni.getStorageSync('store_id')) data.store_id = uni.getStorageSync('store_id');
  19. // 参数
  20. if (params.data != undefined) Object.assign(data, params.data);
  21. if (params.async === false) {
  22. //同步
  23. return new Promise((resolve, reject) => {
  24. uni.request({
  25. url: url,
  26. method: method,
  27. data: data,
  28. header: params.header || {
  29. 'content-type': 'application/x-www-form-urlencoded;application/json'
  30. },
  31. dataType: params.dataType || 'json',
  32. responseType: params.responseType || 'json',
  33. success: (res) => {
  34. if (res.data.code == -10009 || res.data.code == -10010) {
  35. uni.removeStorage({
  36. key: 'cashier_token'
  37. })
  38. if (Util.getCurrRoute() != 'pages/login/login') {
  39. Util.redirectTo('/pages/login/login', {}, 'reLaunch');
  40. return;
  41. }
  42. }
  43. resolve(res.data);
  44. },
  45. fail: (res) => {
  46. reject(res);
  47. },
  48. complete: (res) => {
  49. reject(res);
  50. }
  51. });
  52. }).catch((e) => {});
  53. } else {
  54. //异步
  55. uni.request({
  56. url: url,
  57. method: method,
  58. data: data,
  59. header: params.header || {
  60. 'content-type': 'application/x-www-form-urlencoded;application/json'
  61. },
  62. dataType: params.dataType || 'json',
  63. responseType: params.responseType || 'text',
  64. success: (res) => {
  65. if (res.data.code == -10009 || res.data.code == -10010) {
  66. uni.removeStorage({
  67. key: 'cashier_token'
  68. })
  69. if (Util.getCurrRoute() != 'pages/login/login') {
  70. Util.redirectTo('/pages/login/login', {}, 'reLaunch');
  71. return;
  72. }
  73. }
  74. typeof params.success == 'function' && params.success(res.data);
  75. },
  76. fail: (res) => {
  77. typeof params.fail == 'function' && params.fail(res);
  78. },
  79. complete: (res) => {
  80. typeof params.complete == 'function' && params.complete(res);
  81. }
  82. });
  83. }
  84. }
  85. }