fetch.js 8.1 KB

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