request.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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":"8aaa809d835ba76d018377d482ac0004","sourceType":"WECHAT","phoneNumber":"15090631337","projectId":"","brandId":"8aaa81947c6e1ca0017c73c13cc30006","cid":"oudWQ5ccsJLSlUGt0s_RQysoHqgg","vipCode":"KERRY100213432","lbsId":"8aaa82ea804d07cd0180516ff03b0008"}
  94. if (/orders-and-prepay|calculate-discount|unlicensed-car-check-in|unlicensed-car-checkout/g.test(config.url)) {
  95. params.buildingId = window.localStorage.getItem('buildingId');
  96. }
  97. return JSON.stringify(params);
  98. }
  99. function getSign(config) {
  100. let params = {}
  101. if(config.method === 'get' && config?.params) {
  102. params = config.params
  103. }
  104. if(config.method === 'post' && config?.data) {
  105. params = config.data
  106. }
  107. const newHeader = md(params, true)
  108. return newHeader
  109. }
  110. export const createAxiosByinterceptors = (config) => {
  111. const instance = axios.create({
  112. timeout: 100000, //超时配置
  113. baseURL: `${window.profileApi}/temporary-parking-service`,
  114. // baseURL: `https://dev-kip-service-internal.kerryonvip.com/temporary-parking-service`,
  115. withCredentials: true, //跨域携带cookie
  116. ...config, // 自定义配置覆盖基本配置
  117. });
  118. // 添加请求拦截器
  119. instance.interceptors.request.use(
  120. function (config) {
  121. // 在发送请求之前做些什么
  122. const { loading = true } = config;
  123. if (loading) addLoading();
  124. // 设置 headers
  125. config.headers = {
  126. ...config.headers,
  127. ...handleConfig().header,
  128. // ...getSign(config),
  129. 'x-conversation-id': uuidv4(),
  130. 'X-User': XUser(config),
  131. };
  132. return config;
  133. },
  134. function (error) {
  135. // 对请求错误做些什么
  136. return Promise.reject(error);
  137. }
  138. );
  139. // 添加响应拦截器
  140. instance.interceptors.response.use(
  141. function (response) {
  142. // 对响应数据做点什么
  143. console.log('response:', response);
  144. const { loading = true } = response.config;
  145. if (loading) cancelLoading();
  146. const { code, data, message } = response.data;
  147. console.log('62response', response);
  148. // TODO: 临时注释
  149. // Promise.reject(response.data)
  150. return response.data;
  151. },
  152. function (error) {
  153. // 对响应错误做点什么
  154. console.log('error-response:', error.response);
  155. console.log('error-config:', error.config);
  156. console.log('error-request:', error.request);
  157. const { loading = true } = error.config || {};
  158. if (loading) cancelLoading();
  159. if (error.response) {
  160. if (error.response.status === 401) {
  161. // 跳转到登陆
  162. // jumpLogin();
  163. }
  164. }
  165. // 错误信息提示
  166. const { code, langMessage, message } = error.response.data;
  167. const codeList = ['INTERNAL_SERVER_ERROR', 'VALIDATION_FAILED', 'CAR_NOT_FOUND', 'CAR_HAS_PLATE', "NOT_FOUND", "LOCAL_PARK_ERROR", "LOCK_OCCUPIED", "REMOTE_CALL_FAIL", 'PLEASE_SCAN_QRCODE']; // 默认处理的错误code
  168. if (codeList.indexOf(code) > -1) {
  169. uni.showToast({ title: langMessage || message, duration: 3000, icon: 'fail' });
  170. }
  171. // Message.error(error?.response?.data?.message || '服务端异常');
  172. return Promise.reject(error.response.data);
  173. }
  174. );
  175. return instance;
  176. };