request.ts 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. import Taro from "@tarojs/taro";
  2. interface RequestParam {
  3. url: string;
  4. method: 'POST' | 'GET' | 'DELETE' | 'PUT';
  5. data?: Record<string, any>;
  6. showAlert?: boolean;
  7. }
  8. interface Resp {
  9. statusCode?: number;
  10. header?: any;
  11. data?: any;
  12. errMsg?: string;
  13. };
  14. async function getStorage(key:string) {
  15. try {
  16. const res = await Taro.getStorage({ key });
  17. return res.data;
  18. } catch {
  19. return '';
  20. }
  21. }
  22. export async function request<T>(param: RequestParam): Promise<T> {
  23. const { url, method, data } = param;
  24. let header: any = {};
  25. const token = await getStorage('token')
  26. var split = new Date().toString().split(' ');
  27. var timeZoneFormatted = split[split.length - 2];
  28. header['X-Time-Zone'] = timeZoneFormatted; //new Date().getTimezoneOffset() / 60
  29. if (token.length>0){
  30. header['Authorization'] = `Bearer ${token}`
  31. }
  32. //X-Language:语言,X-Device-Id:设备唯一码,X-Platform:小程序/android/ios,X-Location:地区,X-Device:登录设备
  33. header['X-Language'] = ''
  34. header['X-Device-Id'] = ''
  35. header['X-Platform'] = ''
  36. header['X-Location'] = ''
  37. header['X-Device'] = ''
  38. // header['X-Time-Zone-Id'] = Intl.DateTimeFormat().resolvedOptions().timeZone
  39. // header['Authorization'] = 'Bearer ' + wx.getStorageSync('token');
  40. // header['Authorization'] = 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJhY2NvdW50Iiwic3ViIjoiMmQ5OWNlYzI0ZDFlMzE0Y2U1MjhlODM4MWMzYzk0MzgiLCJpc3MiOiJDT0RFUEFBUy5DT00iLCJuaWNrbmFtZSI6IueOi-a4nSIsInR5cCI6IkJlYXJlciIsInNlc3Npb25fc3RhdGUiOiIyN2RjNmU4ZDdjMWU1MTVmNDQwNzVjZTFlODk2ZmUzNCIsImV4cCI6MTcxNjY0Mzk5MSwiaWF0IjoxNjg1MDIxNTkxfQ.fmFj0OVNRzjLkdebSyGJyk8EScPJFpDiz0L25W35zoA'
  41. return new Promise((resolve, reject) => {
  42. Taro.request({
  43. url: url,
  44. method: method,
  45. header: header,
  46. data: data || {},
  47. success: (response: Resp | { [key: string]: any }) => {
  48. const { statusCode, data } = response;
  49. if (statusCode != 200) {
  50. reject(data);
  51. }
  52. const { error_code } = response.data || {};
  53. if (error_code === 'NOT_LOGIN') {
  54. // new UserManager().logout();
  55. }
  56. const resp = response.data as T;
  57. resolve(resp);
  58. },
  59. fail: err => {
  60. if (err.errMsg == 'request:fail timeout') {
  61. // wx.showToast({
  62. // title: '请求超时',
  63. // icon: 'none',
  64. // });
  65. }
  66. reject(err);
  67. },
  68. complete: () => {},
  69. });
  70. });
  71. }
  72. // import axios from 'axios';
  73. // const kTimeout = 6000;
  74. // const kRetry = 3;
  75. // const axiosInstance = axios.create({
  76. // timeout: kTimeout,
  77. // });
  78. // axios.interceptors.request.use(
  79. // function (config) {
  80. // var split = new Date().toString().split(' ');
  81. // var timeZoneFormatted = split[split.length - 2];
  82. // config.headers['X-Time-Zone'] = timeZoneFormatted;
  83. // // config.headers['channel'] = 'mini program'
  84. // return config
  85. // },
  86. // function (error) {
  87. // return Promise.reject(error)
  88. // }
  89. // )
  90. // axiosInstance.interceptors.response.use(
  91. // response => response,
  92. // error => Promise.reject(error)
  93. // );
  94. // export const request = async (url, method = 'post', data = {}, options = {}) => {
  95. // const { timeout = kTimeout, retry = kRetry } = options;
  96. // axiosInstance.defaults.timeout = timeout;
  97. // let retries = 0;
  98. // while (retries < retry) {
  99. // try {
  100. // const response = await axiosInstance({
  101. // url,
  102. // method,
  103. // data,
  104. // });
  105. // return response.data;
  106. // } catch (error) {
  107. // console.log(error)
  108. // if (axios.isCancel(error)) {
  109. // // 请求被取消
  110. // console.log('Request canceled');
  111. // break;
  112. // }
  113. // if (retries === retry - 1) {
  114. // // 达到最大重试次数
  115. // throw error;
  116. // }
  117. // console.log('Request failed. Retrying...');
  118. // retries++;
  119. // }
  120. // }
  121. // };