fetch.js 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. import '../static/encry.min.js' //接口加密工具
  2. import Vue from 'vue'
  3. function initData(params) {
  4. var URLSearchParams = require('url-search-params');
  5. //360浏览器不支持URLSearchParams
  6. if (typeof URLSearchParams === "function") {
  7. var formMap = new URLSearchParams();
  8. for (var key in params) {
  9. if (typeof (params[key]) == "undefined") {
  10. params[key] = '';
  11. }
  12. formMap.append(key, params[key]);
  13. }
  14. return formMap;
  15. } else {
  16. return params;
  17. }
  18. }
  19. let project = host.PROJECT;
  20. export default async (url = '', baseUrl = '', data = {}, dataType = 'JSON', type = 'GET', pathArr = [], method = 'fetch') => {
  21. type = type.toUpperCase();
  22. if (process.env.NODE_ENV === 'development') {
  23. baseUrl = baseUrl;
  24. } else if (process.env.NODE_ENV === 'production') {
  25. if (baseUrl) {
  26. // let buildUrl = "https://test.hajwy.com/"
  27. let buildUrl = "https://pms.hajwy.com/"
  28. switch (baseUrl) {
  29. case '/landcrm':
  30. // baseUrl = 'https://test.hajwy.com/landcrm';
  31. baseUrl = buildUrl + 'landcrm';
  32. break;
  33. case '/purchase': //
  34. // baseUrl = "https://test.hajwy.com/purchase";
  35. baseUrl = buildUrl + 'purchase';
  36. break;
  37. case '/hajwy': //
  38. // baseUrl = "https://test.hajwy.com/qpi/rest";
  39. baseUrl = buildUrl + 'qpi/rest';
  40. break;
  41. case '/mkf': //
  42. // baseUrl = "https://test.hajwy.com/landcrm";
  43. baseUrl = buildUrl + 'landcrm';
  44. break;
  45. default:
  46. baseUrl = "";
  47. break;
  48. }
  49. }
  50. if (host.PROJECT === 'chuangxinfang') baseUrl = `/wg${baseUrl}`;
  51. }
  52. url = baseUrl + url;
  53. if (pathArr && pathArr.length > 0) {
  54. url += "/" + pathArr.join("/");
  55. }
  56. if (type == 'GET' || type == 'DELETE') {
  57. let dataStr = ''; //数据拼接字符串
  58. Object.keys(data).forEach(key => {
  59. if (typeof (data[key]) == "undefined") {
  60. data[key] = "";
  61. }
  62. dataStr += key + '=' + encodeURIComponent(data[key]) + '&';
  63. })
  64. if (dataStr !== '') {
  65. dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
  66. url = url + '?' + dataStr + '&_t=' + new Date().getTime();
  67. } else {
  68. url = url + '?_t=' + new Date().getTime();
  69. }
  70. }
  71. if (window.fetch && method == 'fetch') {
  72. var header_content = {
  73. 'Accept': 'application/json',
  74. 'Content-Type': 'application/x-www-form-urlencoded',
  75. 'client_token': '',
  76. 'token': ''
  77. };
  78. if (dataType && dataType === "XML") {
  79. header_content = {
  80. 'Accept': 'application/xml',
  81. 'Content-Type': 'application/x-www-form-urlencoded'
  82. };
  83. } else if (dataType && dataType === "JSON2") {
  84. header_content = {
  85. 'Accept': 'application/json',
  86. 'Content-Type': 'application/json'
  87. };
  88. } else if (dataType && dataType === "FORMDATA") {
  89. header_content = {
  90. dataType: "json",
  91. cache: false, //上传文件无需缓存
  92. processData: false, //用于对data参数进行序列化处理 这里必须false
  93. // contentType: "application/x-www-form-urlencoded", //必须
  94. ContentType: "application/x-www-form-urlencoded"
  95. };
  96. }
  97. if (localStorage.token != "" && typeof (localStorage.token) !== "undefined") {
  98. header_content.client_token = localStorage.token;
  99. header_content.token = localStorage.token;
  100. }
  101. header_content.sign = key_gen.encode(key_gen.handlerData(type == 'GET' ? url.substring(url.indexOf("?") + 1) : data));
  102. if (localStorage.user_id) {
  103. header_content["userId"] = localStorage.user_id;
  104. }
  105. let requestConfig = {
  106. credentials: 'include',
  107. method: type,
  108. headers: header_content,
  109. mode: "cors",
  110. cache: "force-cache"
  111. }
  112. if ((type == 'POST' || type == 'PUT' || type == 'DELETE') && dataType != "JSON2" && dataType != "FORMDATA") {
  113. Object.defineProperty(requestConfig, 'body', {
  114. value: initData(data)
  115. })
  116. } else if ((type == 'POST' || type == 'PUT' || type == 'DELETE') && dataType == "JSON2") {
  117. Object.defineProperty(requestConfig, 'body', {
  118. value: JSON.stringify(data)
  119. })
  120. } else if ((type == 'POST') && dataType == "FORMDATA") {
  121. Object.defineProperty(requestConfig, 'body', {
  122. value: data
  123. })
  124. }
  125. try {
  126. const response = await fetch(url, requestConfig);
  127. if (response.headers.get("token_code") == -2 || response.headers.get("token_code") == -1) {
  128. Vue.prototype.$Message.config({
  129. top: 80,
  130. duration: 3
  131. });
  132. console.log("=====账号过期======");
  133. console.log(url);
  134. console.log(requestConfig);
  135. console.log("------end-------");
  136. Vue.prototype.$Message.info("当前账号已过期,请重新登录!");
  137. Vue.prototype.$Message = function (str) {
  138. return;
  139. }
  140. setTimeout(function () {
  141. localStorage.clear();
  142. if (host.PROJECT && host.PROJECT == "xingfujiye") {
  143. window.location.href = "http://csms.cfldcn.com:5902/qpi/logoutFilter?returnUrl=" + Util.filterUrl(window.location.href);
  144. } else {
  145. location.reload();
  146. }
  147. return;
  148. }, 3000);
  149. } else {
  150. if (dataType && dataType === "XML") {
  151. const responseJson = await response.text();
  152. return responseJson
  153. } else {
  154. const responseJson = await response.json();
  155. return responseJson
  156. }
  157. }
  158. } catch (error) {
  159. Vue.prototype.$Spin.hide();
  160. const responseJson = {
  161. errCode: 500,
  162. msg: "系统异常"
  163. };
  164. return responseJson;
  165. }
  166. } else {
  167. return new Promise((resolve, reject) => {
  168. let requestObj;
  169. if (window.XMLHttpRequest) {
  170. requestObj = new XMLHttpRequest();
  171. } else {
  172. requestObj = new ActiveXObject;
  173. }
  174. let sendData = '';
  175. if ((type == 'POST' || type == 'PUT' || type == 'DELETE') && dataType != "JSON2" && dataType != "FORMDATA") {
  176. sendData = initData(data);
  177. } else if ((type == 'POST' || type == 'PUT' || type == 'DELETE') && dataType == "JSON2") {
  178. sendData = JSON.stringify(data);
  179. } else if ((type == 'POST') && dataType == "FORMDATA") {
  180. sendData = data;
  181. }
  182. requestObj.open(type, url, true);
  183. requestObj.setRequestHeader("Accept", "application/json");
  184. if (dataType && dataType === "XML") {
  185. requestObj.setRequestHeader("Accept", "application/xml");
  186. requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  187. } else if (dataType && dataType === "JSON2") {
  188. requestObj.setRequestHeader("Accept", "application/json");
  189. requestObj.setRequestHeader("Content-type", "application/json");
  190. } else if (dataType && dataType === "FORMDATA") {
  191. requestObj.setRequestHeader("Accept", "application/json");
  192. requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  193. requestObj.setRequestHeader("dataType", "json");
  194. requestObj.setRequestHeader("cache", false); //上传文件无需缓存
  195. requestObj.setRequestHeader("processData", false); //用于对data参数进行序列化处理 这里必须false
  196. requestObj.setRequestHeader("contentType", false); //必须
  197. } else {
  198. requestObj.setRequestHeader("Accept", "application/json");
  199. requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  200. }
  201. requestObj.setRequestHeader("client_token", localStorage.token || "");
  202. requestObj.setRequestHeader("token", localStorage.token || "");
  203. requestObj.setRequestHeader("sign", key_gen.encode(key_gen.handlerData(type == 'GET' ? url.substring(url.indexOf("?") + 1) : data)));
  204. if (localStorage.user_id) {
  205. requestObj.setRequestHeader("x-user-id-header", localStorage.user_id);
  206. }
  207. requestObj.send(sendData);
  208. requestObj.onreadystatechange = () => {
  209. if (requestObj.readyState == 4) {
  210. if (requestObj.status == 200) {
  211. let obj = requestObj.response || requestObj.responseT
  212. if (typeof obj !== 'object' && obj.indexOf("<?xml") == -1) {
  213. obj = JSON.parse(obj);
  214. }
  215. resolve(obj)
  216. }
  217. }
  218. }
  219. })
  220. }
  221. }