request.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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. // https://kerryprops.atlassian.net/browse/KIP-10831
  93. sourceId: store.state?.sourceId || '', // 微信:unionId; 支付宝:userId
  94. // isLogin: store.state?.member?.vipcode ? true : false
  95. isLogin: store.state?.isLogin === 'haveLoggedIn'
  96. };
  97. // params = {"userId": "8aaa809d835ba76d018378bc57180006","sourceType": "WECHAT","phoneNumber": "18521563898","projectId": "paroject1","buildingId": "QHKC-P1","brandId":"8a84853b7c91ac5b017c962dab55030e","cid": "oIUfO5XAVleJ88z13i1_08DCKIhQ","vipCode":"KERRY100200040","lbsId":"8aaa81cb7c836c6b017c83e46b110001"}
  98. if (/orders-and-prepay|calculate-discount|unlicensed-car-check-in|unlicensed-car-checkout|paper-coupon/g.test(config.url)) {
  99. params.buildingId = window.localStorage.getItem('buildingId');
  100. }
  101. const newParams = {}
  102. Object.keys(params).forEach(key => {
  103. const value = params[key]
  104. // 对特殊字段,不做过滤处理
  105. if ( value || key === 'isLogin') {
  106. newParams[key] = value
  107. }
  108. })
  109. return JSON.stringify(newParams);
  110. }
  111. function getSign(config) {
  112. let params = {}
  113. if(config.method === 'get' && config?.params) {
  114. params = config.params
  115. }
  116. if(config.method === 'post' && config?.data) {
  117. params = config.data
  118. }
  119. const newHeader = md(params, true)
  120. return newHeader
  121. }
  122. export const createAxiosByinterceptors = (config) => {
  123. const instance = axios.create({
  124. timeout: 1000000, //超时配置
  125. baseURL: `${window.profileApi}/temporary-parking-service`,
  126. // baseURL: `https://dev-kip-service-internal.kerryonvip.com/temporary-parking-service`,
  127. withCredentials: false, //跨域携带cookie
  128. xhrFields: {
  129. withCredentials: false // 允许跨域携带cookie信息
  130. },
  131. ...config, // 自定义配置覆盖基本配置
  132. });
  133. // 添加请求拦截器
  134. instance.interceptors.request.use(
  135. function (config) {
  136. // 在发送请求之前做些什么
  137. const { loading = true } = config;
  138. if (loading) addLoading();
  139. // 设置 headers
  140. config.headers = {
  141. ...config.headers,
  142. ...handleConfig().header,
  143. // ...getSign(config),
  144. // 'x-conversation-id': uuidv4(),
  145. 'Parking-User': XUser(config),
  146. 'withCredentials': 'false'
  147. };
  148. return config;
  149. },
  150. function (error) {
  151. // 对请求错误做些什么
  152. return Promise.reject(error);
  153. }
  154. );
  155. // 添加响应拦截器
  156. instance.interceptors.response.use(
  157. function (response) {
  158. // 对响应数据做点什么
  159. console.log('response:', response);
  160. const { loading = true } = response.config;
  161. if (loading) cancelLoading();
  162. const { code, data, message, langMessage } = response.data;
  163. console.log('success response', response);
  164. const codeList = ['010902']
  165. if (codeList.indexOf(code) > -1) {
  166. uni.showToast({ title: langMessage || message, duration: 3000, icon: 'fail' });
  167. }
  168. // TODO: 临时注释
  169. // Promise.reject(response.data)
  170. return response.data;
  171. },
  172. function (error) {
  173. console.log('error', error);
  174. // 断网
  175. if (error.code === 'ERR_NETWORK') {
  176. uni.showToast({ title: '网络连接失败,请重试', duration: 3000, icon: 'fail' });
  177. return Promise.reject(error.code);
  178. }
  179. // 对响应错误做点什么
  180. console.log('error-response:', error.response);
  181. console.log('error-config:', error.config);
  182. console.log('error-request:', error.request);
  183. const { loading = true } = error.config || {};
  184. if (loading) cancelLoading();
  185. if (error.response) {
  186. if (error.response.status === 401) {
  187. // 跳转到登陆
  188. // jumpLogin();
  189. }
  190. }
  191. // 错误信息提示
  192. const { code, langMessage, message,status } = error.response.data;
  193. 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
  194. if (codeList.indexOf(code) > -1) {
  195. uni.showToast({ title: langMessage || message, duration: 3000, icon: 'fail' });
  196. }
  197. if ( status === 500 ) {
  198. uni.showToast({ title: error.response.data.error, duration: 3000, icon: 'fail' });
  199. }
  200. // Message.error(error?.response?.data?.message || '服务端异常');
  201. return Promise.reject(error.response.data);
  202. }
  203. );
  204. return instance;
  205. };