fetch.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. import '../static/encry.min.js' //接口加密工具
  2. import Vue from 'vue'
  3. import Util from "../src/assets/js/util";
  4. import {
  5. router
  6. } from '../src/router'
  7. function initData(params) {
  8. var URLSearchParams = require('url-search-params');
  9. //360浏览器不支持URLSearchParams
  10. if (typeof URLSearchParams === "function") {
  11. var formMap = new URLSearchParams();
  12. for (var key in params) {
  13. if (typeof (params[key]) == "undefined") {
  14. params[key] = '';
  15. }
  16. formMap.append(key, params[key]);
  17. }
  18. return formMap;
  19. } else {
  20. return params;
  21. }
  22. }
  23. export default async (url = '', baseUrl = '', data = {}, dataType = 'JSON', type = 'GET', method = 'fetch') => {
  24. type = type.toUpperCase();
  25. if (process.env.NODE_ENV === 'development') {
  26. baseUrl = baseUrl;
  27. } else if (process.env.NODE_ENV === 'production') {
  28. if (baseUrl) {
  29. switch (baseUrl) {
  30. case '/landcrm':
  31. baseUrl = '/landcrm'; //其他环境
  32. break;
  33. case '/rcrm':
  34. baseUrl = '/landcrm'; //报表地址
  35. break;
  36. case '/decorationManage': //装修
  37. baseUrl = '/decorationManage';
  38. break;
  39. case '/engineManage': //工程
  40. baseUrl = '/engineManage';
  41. break;
  42. default:
  43. baseUrl = "";
  44. break;
  45. }
  46. }
  47. }
  48. if (host.PROJECT === 'chuangxinfang') {
  49. const host = window.location.hostname;
  50. switch (host) {
  51. case 'www.novotown.com.cn':
  52. baseUrl = `/wg${baseUrl}`;
  53. break
  54. }
  55. }
  56. url = baseUrl + url;
  57. if (type == 'GET') {
  58. let dataStr = ''; //数据拼接字符串
  59. Object.keys(data).forEach(key => {
  60. if (typeof (data[key]) == "undefined") {
  61. data[key] = "";
  62. }
  63. dataStr += key + '=' + data[key] + '&';
  64. })
  65. if (dataStr !== '') {
  66. dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
  67. url = url + '?' + dataStr + '&_t=' + new Date().getTime();
  68. } else {
  69. url = url + (url.indexOf('?') > -1 ? '&_t=' + new Date().getTime() : '?_t=' + new Date().getTime());
  70. }
  71. }
  72. if (window.fetch && method == 'fetch') {
  73. var header_content = {
  74. 'Accept': 'application/json',
  75. 'Content-Type': 'application/x-www-form-urlencoded',
  76. 'client_token': '',
  77. 'token': '',
  78. };
  79. if (localStorage.token != "" && typeof (localStorage.token) !== "undefined") {
  80. header_content.client_token = localStorage.token;
  81. header_content.token = localStorage.token;
  82. }
  83. if (localStorage.user_id != "" && typeof (localStorage.user_id) !== "undefined") {
  84. header_content.userId = localStorage.user_id;
  85. }
  86. if (localStorage.companyId != "" && typeof (localStorage.companyId) !== "undefined") {
  87. header_content.companyId = localStorage.companyId;
  88. }
  89. header_content.sign = key_gen.encode(key_gen.handlerData(type == 'GET' ? url.substring(url.indexOf("?") + 1) : data));
  90. if (dataType && dataType === "XML") {
  91. header_content = {
  92. 'Accept': 'application/xml',
  93. 'Content-Type': 'application/x-www-form-urlencoded'
  94. };
  95. } else if (dataType && dataType === "JSON2") {
  96. header_content = {
  97. 'Accept': 'application/json',
  98. 'Content-Type': 'application/json',
  99. 'token': localStorage.token,
  100. };
  101. } else if (dataType && dataType === "FORMDATA") {
  102. header_content = {
  103. dataType: "json",
  104. cache: false, //上传文件无需缓存
  105. processData: false, //用于对data参数进行序列化处理 这里必须false
  106. contentType: false, //必须
  107. };
  108. }
  109. // 空置房管理接口 头部必须含有userId以及userName
  110. if (baseUrl == '/vacant') {
  111. if (localStorage.user_id && localStorage.user_id != "") {
  112. header_content.userId = localStorage.user_id;
  113. header_content.userName = encodeURI(localStorage.user_name);
  114. }
  115. }
  116. if (localStorage.companyId != "" && typeof (localStorage.companyId) !== "undefined") {
  117. header_content.companyId = localStorage.companyId;
  118. }
  119. if (localStorage.user_id != "" && typeof (localStorage.user_id) !== "undefined") {
  120. header_content.userId = localStorage.user_id;
  121. }
  122. let requestConfig = {
  123. credentials: 'include',
  124. method: type,
  125. headers: header_content,
  126. mode: "cors",
  127. cache: "force-cache"
  128. }
  129. if ((type == 'POST' || type == 'PUT' || type == 'DELETE') && dataType != "JSON2" && dataType != "FORMDATA") {
  130. Object.defineProperty(requestConfig, 'body', {
  131. value: initData(data)
  132. })
  133. } else if ((type == 'POST' || type == 'PUT' || type == 'DELETE') && dataType == "JSON2") {
  134. Object.defineProperty(requestConfig, 'body', {
  135. value: JSON.stringify(data)
  136. })
  137. } else if ((type == 'POST') && dataType == "FORMDATA") {
  138. Object.defineProperty(requestConfig, 'body', {
  139. value: data
  140. })
  141. }
  142. // if (type == 'POST') {
  143. // Object.defineProperty(requestConfig, 'body', {
  144. // value: initData(data)
  145. // })
  146. // }
  147. //if (type == 'POST') {
  148. // Object.defineProperty(requestConfig, 'body', {
  149. // value: JSON.stringify(data)
  150. // })
  151. //}
  152. try {
  153. const response = await fetch(url, requestConfig);
  154. if (response.headers.get("token_code") == -2 || response.headers.get("token_code") == -1) {
  155. // alert("当前账号已过期,请重新登录!");
  156. // window.alert=function(str){return;}
  157. Vue.prototype.$Message.config({
  158. top: 80,
  159. duration: 3
  160. });
  161. Vue.prototype.$Message.info("当前账号已过期,请重新登录!");
  162. Vue.prototype.$Message = function (str) {
  163. return;
  164. }
  165. //TODO:这里的注释回头得改回来
  166. setTimeout(function () {
  167. localStorage.clear();
  168. if (host.PROJECT && host.PROJECT == "xingfujiye") {
  169. window.location.href = "http://csms.cfldcn.com:5902/qpi/logoutFilter?returnUrl=" + Util.filterUrl(window.location.href);
  170. } else {
  171. location.reload();
  172. }
  173. return;
  174. }, 3000);
  175. } else if (response.headers.get("securitycode") && response.headers.get("securitycode") == 0) {
  176. //0.未通过; -1.不验证; 1.通过;
  177. Vue.prototype.$Message.config({
  178. top: 80,
  179. duration: 3
  180. });
  181. Vue.prototype.$Message.info("非法请求");
  182. //TODO:这里的注释回头得改回来
  183. setTimeout(function () {
  184. localStorage.clear();
  185. if (host.PROJECT && host.PROJECT == "xingfujiye") {
  186. window.location.href = "http://csms.cfldcn.com:5902/qpi/logoutFilter?returnUrl=" + Util.filterUrl(window.location.href);
  187. } else {
  188. location.reload();
  189. }
  190. return;
  191. }, 3000);
  192. } else {
  193. //TODO:这里的注释回头得改回来
  194. if (dataType && dataType === "XML") {
  195. const responseJson = await response.text();
  196. return responseJson
  197. } else {
  198. const responseJson = await response.json();
  199. if (responseJson.status == '401') {
  200. localStorage.clear();
  201. sessionStorage.clear();
  202. location.reload();
  203. }
  204. return responseJson
  205. }
  206. }
  207. } catch (error) {
  208. Vue.prototype.$Spin.hide();
  209. const responseJson = {
  210. errCode: 500,
  211. msg: "系统异常"
  212. };
  213. return responseJson;
  214. // throw new Error(error)
  215. }
  216. } else {
  217. return new Promise((resolve, reject) => {
  218. let requestObj;
  219. if (window.XMLHttpRequest) {
  220. requestObj = new XMLHttpRequest();
  221. } else {
  222. requestObj = new ActiveXObject;
  223. }
  224. let sendData = '';
  225. // if (type == 'POST') {
  226. // console.log(data)
  227. // Object.keys(data).forEach(key => {
  228. // sendData += key + '=' + data[key] + '&';
  229. // })
  230. // sendData = sendData.substr(0, sendData.lastIndexOf('&'));
  231. // }
  232. if ((type == 'POST' || type == 'PUT' || type == 'DELETE') && dataType != "JSON2" && dataType != "FORMDATA") {
  233. sendData = initData(data)
  234. } else if ((type == 'POST' || type == 'PUT' || type == 'DELETE') && dataType == "JSON2") {
  235. sendData = JSON.stringify(data)
  236. } else if ((type == 'POST') && dataType == "FORMDATA") {
  237. sendData = data
  238. }
  239. requestObj.open(type, url, true);
  240. if (dataType && dataType === "XML") {
  241. requestObj.setRequestHeader("Accept", "application/xml");
  242. requestObj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  243. } else if (dataType && dataType === "JSON2") {
  244. requestObj.setRequestHeader("Accept", "application/json");
  245. requestObj.setRequestHeader("Content-Type", "application/json");
  246. } else if (dataType && dataType === "FORMDATA") {
  247. requestObj.setRequestHeader("Accept", "application/json");
  248. requestObj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  249. requestObj.setRequestHeader("dataType", "json");
  250. requestObj.setRequestHeader("cache", false); //上传文件无需缓存
  251. requestObj.setRequestHeader("processData", false); //用于对data参数进行序列化处理 这里必须false
  252. requestObj.setRequestHeader("contentType", false); //必须
  253. }
  254. requestObj.setRequestHeader("sign", key_gen.encode(key_gen.handlerData(type == 'GET' ? url.substring(url.indexOf("?") + 1) : data)));
  255. if (localStorage.token != "" && typeof (localStorage.token) !== "undefined") {
  256. requestObj.setRequestHeader("token", localStorage.token);
  257. requestObj.setRequestHeader("client_token", localStorage.token);
  258. }
  259. if (localStorage.companyId != "" && typeof (localStorage.companyId) !== "undefined") {
  260. requestObj.setRequestHeader("companyId", localStorage.companyId);
  261. }
  262. if (localStorage.user_id != "" && typeof (localStorage.user_id) !== "undefined") {
  263. requestObj.setRequestHeader("user_id", localStorage.user_id);
  264. }
  265. requestObj.send(sendData);
  266. requestObj.onreadystatechange = () => {
  267. if (requestObj.readyState == 4) {
  268. if (requestObj.status == 200) {
  269. let obj = requestObj.response || requestObj.responseT
  270. if (typeof obj !== 'object' && obj.indexOf("<?xml") == -1) {
  271. obj = JSON.parse(obj);
  272. }
  273. resolve(obj)
  274. }
  275. }
  276. }
  277. })
  278. }
  279. }