request.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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. console.log(24, '接口返送出去的config', config);
  23. const { contentType = 'json' } = config;
  24. const ct = CONTENT_TYPE_ARRAY[contentType];
  25. let header = {
  26. // appId: uni.getStorageSync('appid'),
  27. appId: 'wx92c3e55fbef6b2af',
  28. 'Content-Type': ct,
  29. };
  30. const token = getToken();
  31. if (token) {
  32. header['Authorization'] = `Bearer ${token}`;
  33. }
  34. const groupId = uni.getStorageSync('groupId');
  35. const mallId = uni.getStorageSync('mallid');
  36. if (groupId) {
  37. header['brandId'] = groupId;
  38. }
  39. if (mallId) {
  40. header['lbsId'] = mallId;
  41. }
  42. const sourceObj = getUTMSource();
  43. return Object.assign(header, sourceObj);
  44. }
  45. function handleConfig(config = {}) {
  46. const header = getHeaders(config);
  47. const noToken = config.noToken;
  48. if (noToken) {
  49. delete header.Authorization;
  50. }
  51. console.log(525252, header);
  52. return { header, ...config };
  53. }
  54. function getToken() {
  55. const token = uni.getStorageSync('kipAccessToken');
  56. // if (!token || token?.trim() == '' || token == 'null' || token == 'undefined') {
  57. if (!token || token == 'null' || token == 'undefined') {
  58. return false;
  59. }
  60. return token;
  61. }
  62. const addLoading = () => {
  63. // 增加loading 如果pending请求数量等于1,弹出loading, 防止重复弹出
  64. requestNum++;
  65. if (requestNum === 1) {
  66. // 展示加载中的状态
  67. loadingInstance = Toast.loading({
  68. message: '正在努力加载中....',
  69. });
  70. }
  71. };
  72. const cancelLoading = () => {
  73. // 取消loading 如果pending请求数量等于0,关闭loading
  74. requestNum--;
  75. if (requestNum === 0) loadingInstance?.clear();
  76. };
  77. function XUser(config) {
  78. let params = {
  79. userId: store.state?.kipUserId || '', // K+用户ID
  80. // userId: '2c9d85868652dee50186532bdbbb0001', // K+用户ID
  81. sourceType: 'WECHAT',
  82. // phoneNumber: '18521563898',
  83. phoneNumber: store.state?.mobile || '', // 终端用户ID, 微信端传openId, 支付宝小程序传阿里userId, APP传KIP的userId
  84. // projectId: store.state.projectId || '4028e3817c2b3f79017c2b48c54c0000', // 楼盘id
  85. projectId: store.state.projectId || '', // 楼盘id
  86. brandId: store.state.groupId,
  87. // cid: '8aaa809d835ba76d018378bc57180006',
  88. cid: store.state?.openid || '', // 终端用户ID, 微信端传openId, 支付宝小程序传阿里userId, APP传KIP的userId
  89. // vipCode: 'KERRY100213505',
  90. vipCode: store.state?.member?.vipcode || '', // 终端用户ID, 微信端传openId, 支付宝小程序传阿里userId, APP传KIP的userId
  91. // vipCode: 'KERRY100213853', // 终端用户ID, 微信端传openId, 支付宝小程序传阿里userId, APP传KIP的userId
  92. // lbsId: '8aaa82ea804d07cd0180516ff03b0008',
  93. lbsId: store.state?.lbsId || '',
  94. };
  95. // params = {"userId":"8aaa809d835ba76d018377d482ac0004","sourceType":"WECHAT","phoneNumber":"15090631337","projectId":"","brandId":"8aaa81947c6e1ca0017c73c13cc30006","cid":"oudWQ5ccsJLSlUGt0s_RQysoHqgg","vipCode":"KERRY100213432","lbsId":"8aaa82ea804d07cd0180516ff03b0008"}
  96. if (/orders-and-prepay|calculate-discount|unlicensed-car-check-in/.test(config.url)) {
  97. params.buildingId = window.localStorage.getItem('buildingId');
  98. }
  99. return JSON.stringify(params);
  100. }
  101. function getSign(config) {
  102. let params = {}
  103. if(config.method === 'get' && config?.params) {
  104. params = config.params
  105. }
  106. if(config.method === 'post' && config?.data) {
  107. params = config.data
  108. }
  109. const newHeader = md(params, true)
  110. return newHeader
  111. }
  112. export const createAxiosByinterceptors = (config) => {
  113. const instance = axios.create({
  114. timeout: 100000, //超时配置
  115. baseURL: `${window.profileApi}/temporary-parking-service`,
  116. // baseURL: `https://dev-kip-service-internal.kerryonvip.com/temporary-parking-service`,
  117. withCredentials: true, //跨域携带cookie
  118. ...config, // 自定义配置覆盖基本配置
  119. });
  120. // 添加请求拦截器
  121. instance.interceptors.request.use(
  122. function (config) {
  123. // 在发送请求之前做些什么
  124. const { loading = true } = config;
  125. if (loading) addLoading();
  126. // 设置 headers
  127. config.headers = {
  128. ...config.headers,
  129. ...handleConfig().header,
  130. ...getSign(config),
  131. 'XConversationId': uuidv4(),
  132. 'X-User': XUser(config),
  133. };
  134. return config;
  135. },
  136. function (error) {
  137. // 对请求错误做些什么
  138. return Promise.reject(error);
  139. }
  140. );
  141. // 添加响应拦截器
  142. instance.interceptors.response.use(
  143. function (response) {
  144. // 对响应数据做点什么
  145. console.log('response:', response);
  146. const { loading = true } = response.config;
  147. if (loading) cancelLoading();
  148. const { code, data, message } = response.data;
  149. console.log('62response', response);
  150. // TODO: 临时注释
  151. // Promise.reject(response.data)
  152. return response.data;
  153. },
  154. function (error) {
  155. // 对响应错误做点什么
  156. console.log('error-response:', error.response);
  157. console.log('error-config:', error.config);
  158. console.log('error-request:', error.request);
  159. const { loading = true } = error.config || {};
  160. if (loading) cancelLoading();
  161. if (error.response) {
  162. if (error.response.status === 401) {
  163. // 跳转到登陆
  164. // jumpLogin();
  165. }
  166. }
  167. // 错误信息提示
  168. const { code, langMessage, message } = error.response.data;
  169. const codeList = ['INTERNAL_SERVER_ERROR', 'VALIDATION_FAILED', 'CAR_NOT_FOUND', 'CAR_HAS_PLATE', "NOT_FOUND", "LOCAL_PARK_ERROR"]; // 默认处理的错误code
  170. if (codeList.indexOf(code) > -1) {
  171. uni.showToast({ title: langMessage || message, duration: 3000, icon: 'fail' });
  172. }
  173. // Message.error(error?.response?.data?.message || '服务端异常');
  174. return Promise.reject(error.response.data);
  175. }
  176. );
  177. return instance;
  178. };