request.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. import uni from '@/utils/uniHooks';
  2. import { getUTMSource } from '@/utils/utils';
  3. import axios, { AxiosInstance, AxiosRequestConfig } from 'axios';
  4. import {md} from '@/utils/common'
  5. // import { Message } from 'element-ui';
  6. // import { jumpLogin } from '@/utils';
  7. // import { Loading } from 'element-ui';
  8. // import { ElLoadingComponent } from 'element-ui/types/loading';
  9. // import vm from "@/main";
  10. import { Toast } from 'vant';
  11. // import vue from 'vue';
  12. import store from '@/store';
  13. // import { v4 as uuidv4 } from 'uuid';
  14. // import { wxToLoginCallback } from '@/utils/index.js'
  15. let loadingInstance = null;
  16. let requestNum = 0;
  17. const CONTENT_TYPE_ARRAY = {
  18. json: 'application/json',
  19. form: 'application/x-www-form-urlencoded',
  20. };
  21. function getHeaders(config = {}) {
  22. const { contentType = 'json' } = config;
  23. const ct = CONTENT_TYPE_ARRAY[contentType];
  24. let header = {
  25. // appId: uni.getStorageSync('appid'),
  26. // appId: 'wx92c3e55fbef6b2af',
  27. // 'Content-Type': ct,
  28. };
  29. const token = getToken();
  30. if (token) {
  31. header['Authorization'] = `Bearer ${token}`;
  32. }
  33. const groupId = uni.getStorageSync('groupId');
  34. const mallId = uni.getStorageSync('mallid');
  35. // if (groupId) {
  36. // header['brandId'] = groupId;
  37. // }
  38. // if (mallId) {
  39. // header['lbsId'] = mallId;
  40. // }
  41. const sourceObj = getUTMSource();
  42. return Object.assign(header, sourceObj);
  43. }
  44. function handleConfig(config = {}) {
  45. const header = getHeaders(config);
  46. const noToken = config.noToken;
  47. if (noToken) {
  48. delete header.Authorization;
  49. }
  50. return { header, ...config };
  51. }
  52. function getToken() {
  53. const token = uni.getStorageSync('kipAccessToken');
  54. // if (!token || token?.trim() == '' || token == 'null' || token == 'undefined') {
  55. if (!token || token == 'null' || token == 'undefined') {
  56. return false;
  57. }
  58. return token;
  59. }
  60. const addLoading = () => {
  61. // 增加loading 如果pending请求数量等于1,弹出loading, 防止重复弹出
  62. requestNum++;
  63. if (requestNum === 1) {
  64. // 展示加载中的状态
  65. loadingInstance = Toast.loading({
  66. message: '正在努力加载中....',
  67. });
  68. }
  69. };
  70. const cancelLoading = () => {
  71. // 取消loading 如果pending请求数量等于0,关闭loading
  72. requestNum--;
  73. if (requestNum === 0) loadingInstance?.clear();
  74. };
  75. function XUser(config) {
  76. let params = {
  77. userId: store.state?.kipUserId || '', // K+用户ID
  78. // userId: '2c9d85868652dee50186532bdbbb0001', // K+用户ID
  79. sourceType: 'WECHAT',
  80. // phoneNumber: '18521563898',
  81. phoneNumber: store.state?.mobile || '', // 终端用户ID, 微信端传openId, 支付宝小程序传阿里userId, APP传KIP的userId
  82. // projectId: store.state.projectId || '4028e3817c2b3f79017c2b48c54c0000', // 楼盘id
  83. projectId: store.state.projectId || '', // 楼盘id
  84. brandId: store.state.groupId,
  85. // cid: '8aaa809d835ba76d018378bc57180006',
  86. cid: store.state?.openid || '', // 终端用户ID, 微信端传openId, 支付宝小程序传阿里userId, APP传KIP的userId
  87. // vipCode: 'KERRY100213505',
  88. vipCode: store.state?.member?.vipcode || '', // 终端用户ID, 微信端传openId, 支付宝小程序传阿里userId, APP传KIP的userId
  89. // vipCode: 'KERRY100213853', // 终端用户ID, 微信端传openId, 支付宝小程序传阿里userId, APP传KIP的userId
  90. // lbsId: '8aaa82ea804d07cd0180516ff03b0008',
  91. lbsId: store.state?.lbsId || '',
  92. };
  93. // params = {"userId": "8aaa809d835ba76d018378bc57180006","sourceType": "WECHAT","phoneNumber": "18521563898","projectId": "paroject1","buildingId": "QHKC-P1","brandId":"8a84853b7c91ac5b017c962dab55030e","cid": "oIUfO5XAVleJ88z13i1_08DCKIhQ","vipCode":"KERRY100200040","lbsId":"8aaa81cb7c836c6b017c83e46b110001"}
  94. if (/orders-and-prepay|calculate-discount|unlicensed-car-check-in|unlicensed-car-checkout|paper-coupon/g.test(config.url)) {
  95. params.buildingId = window.localStorage.getItem('buildingId');
  96. }
  97. const newParams = {}
  98. Object.keys(params).forEach(key => {
  99. const value = params[key]
  100. if ( value ) {
  101. newParams[key] = value
  102. }
  103. })
  104. return JSON.stringify(newParams);
  105. }
  106. function getSign(config) {
  107. let params = {}
  108. if(config.method === 'get' && config?.params) {
  109. params = config.params
  110. }
  111. if(config.method === 'post' && config?.data) {
  112. params = config.data
  113. }
  114. const newHeader = md(params, true)
  115. return newHeader
  116. }
  117. export const createAxiosByinterceptors = (config) => {
  118. const instance = axios.create({
  119. timeout: 1000000, //超时配置
  120. baseURL: `${window.profileApi}/temporary-parking-service`,
  121. // baseURL: `https://dev-kip-service-internal.kerryonvip.com/temporary-parking-service`,
  122. withCredentials: false, //跨域携带cookie
  123. xhrFields: {
  124. withCredentials: false // 允许跨域携带cookie信息
  125. },
  126. ...config, // 自定义配置覆盖基本配置
  127. });
  128. // 添加请求拦截器
  129. instance.interceptors.request.use(
  130. function (config) {
  131. // 在发送请求之前做些什么
  132. const { loading = true } = config;
  133. if (loading) addLoading();
  134. // 设置 headers
  135. config.headers = {
  136. ...config.headers,
  137. ...handleConfig().header,
  138. // ...getSign(config),
  139. // 'x-conversation-id': uuidv4(),
  140. 'X-User': XUser(config),
  141. 'withCredentials': 'false'
  142. };
  143. return config;
  144. },
  145. function (error) {
  146. // 对请求错误做些什么
  147. return Promise.reject(error);
  148. }
  149. );
  150. // 添加响应拦截器
  151. instance.interceptors.response.use(
  152. function (response) {
  153. // 对响应数据做点什么
  154. console.log('response:', response);
  155. const { loading = true } = response.config;
  156. if (loading) cancelLoading();
  157. const { code, data, message, langMessage } = response.data;
  158. console.log('success response', response);
  159. const codeList = ['010902']
  160. if (codeList.indexOf(code) > -1) {
  161. uni.showToast({ title: langMessage || message, duration: 3000, icon: 'fail' });
  162. }
  163. // TODO: 临时注释
  164. // Promise.reject(response.data)
  165. return response.data;
  166. },
  167. function (error) {
  168. console.log('error', error);
  169. // 断网
  170. if (error.code === 'ERR_NETWORK') {
  171. uni.showToast({ title: '网络连接失败,请重试', duration: 3000, icon: 'fail' });
  172. return Promise.reject(error.code);
  173. }
  174. // 对响应错误做点什么
  175. console.log('error-response:', error.response);
  176. console.log('error-config:', error.config);
  177. console.log('error-request:', error.request);
  178. const { loading = true } = error.config || {};
  179. if (loading) cancelLoading();
  180. if (error.response) {
  181. if (error.response.status === 401) {
  182. // 跳转到登陆
  183. // jumpLogin();
  184. }
  185. }
  186. // 错误信息提示
  187. const { code, langMessage, message,status } = error.response.data;
  188. const codeList = ['INTERNAL_SERVER_ERROR', 'VALIDATION_FAILED', 'CAR_HAS_PLATE', "NOT_FOUND", "LOCAL_PARK_ERROR", "LOCK_OCCUPIED", "REMOTE_CALL_FAIL", 'PLEASE_SCAN_QRCODE', 'SUBIN_CAR_IN_DEVICE_EXCEPTION', 'COUPON_UNAVAILABLE', 'COUPON_SELECTION_FAILED' ]; // 默认处理的错误code
  189. if (codeList.indexOf(code) > -1) {
  190. uni.showToast({ title: langMessage || message, duration: 3000, icon: 'fail' });
  191. }
  192. if ( status === 500 ) {
  193. uni.showToast({ title: error.response.data.error, duration: 3000, icon: 'fail' });
  194. }
  195. // Message.error(error?.response?.data?.message || '服务端异常');
  196. return Promise.reject(error.response.data);
  197. }
  198. );
  199. return instance;
  200. };