fetch.js 8.0 KB

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