fetch.js 7.9 KB

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