fetch.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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. default:
  40. baseUrl = "";
  41. break;
  42. }
  43. }
  44. }
  45. if (host.PROJECT === 'chuangxinfang') {
  46. const host = window.location.hostname;
  47. switch (host) {
  48. case 'www.novotown.com.cn':
  49. baseUrl = `/wg${baseUrl}`;
  50. break
  51. }
  52. }
  53. url = baseUrl + url;
  54. if (type == 'GET') {
  55. let dataStr = ''; //数据拼接字符串
  56. Object.keys(data).forEach(key => {
  57. if (typeof (data[key]) == "undefined") {
  58. data[key] = "";
  59. }
  60. dataStr += key + '=' + 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 + (url.indexOf('?') > -1 ? '&_t=' + new Date().getTime() : '?_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 (localStorage.token != "" && typeof (localStorage.token) !== "undefined") {
  77. header_content.client_token = localStorage.token;
  78. header_content.token = localStorage.token;
  79. }
  80. // if (localStorage.companyId != "" && typeof (localStorage.companyId) !== "undefined") {
  81. // header_content.companyId = localStorage.companyId;
  82. // }
  83. // if (localStorage.user_id != "" && typeof (localStorage.user_id) !== "undefined") {
  84. // header_content.userId = localStorage.user_id;
  85. // }
  86. header_content.sign = key_gen.encode(key_gen.handlerData(type == 'GET' ? url.substring(url.indexOf("?") + 1) : data));
  87. if (dataType && dataType === "XML") {
  88. header_content = {
  89. 'Accept': 'application/xml',
  90. 'Content-Type': 'application/x-www-form-urlencoded'
  91. };
  92. } else if (dataType && dataType === "JSON2") {
  93. header_content = {
  94. 'Accept': 'application/json',
  95. 'Content-Type': 'application/json',
  96. 'token': localStorage.token,
  97. };
  98. } else if (dataType && dataType === "FORMDATA") {
  99. header_content = {
  100. dataType: "json",
  101. cache: false, //上传文件无需缓存
  102. processData: false, //用于对data参数进行序列化处理 这里必须false
  103. contentType: false, //必须
  104. };
  105. }
  106. // 空置房管理接口 头部必须含有userId以及userName
  107. if (baseUrl == '/vacant') {
  108. if (localStorage.user_id && localStorage.user_id != "") {
  109. header_content.userId = localStorage.user_id;
  110. header_content.userName = encodeURI(localStorage.user_name);
  111. }
  112. }
  113. if (localStorage.companyId != "" && typeof (localStorage.companyId) !== "undefined") {
  114. header_content.companyId = localStorage.companyId;
  115. }
  116. if (localStorage.user_id != "" && typeof (localStorage.user_id) !== "undefined") {
  117. header_content.userId = localStorage.user_id;
  118. }
  119. let requestConfig = {
  120. credentials: 'include',
  121. method: type,
  122. headers: header_content,
  123. mode: "cors",
  124. cache: "force-cache"
  125. }
  126. if ((type == 'POST' || type == 'PUT' || type == 'DELETE') && dataType != "JSON2" && dataType != "FORMDATA") {
  127. Object.defineProperty(requestConfig, 'body', {
  128. value: initData(data)
  129. })
  130. } else if ((type == 'POST' || type == 'PUT' || type == 'DELETE') && dataType == "JSON2") {
  131. Object.defineProperty(requestConfig, 'body', {
  132. value: JSON.stringify(data)
  133. })
  134. } else if ((type == 'POST') && dataType == "FORMDATA") {
  135. Object.defineProperty(requestConfig, 'body', {
  136. value: data
  137. })
  138. }
  139. // if (type == 'POST') {
  140. // Object.defineProperty(requestConfig, 'body', {
  141. // value: initData(data)
  142. // })
  143. // }
  144. //if (type == 'POST') {
  145. // Object.defineProperty(requestConfig, 'body', {
  146. // value: JSON.stringify(data)
  147. // })
  148. //}
  149. try {
  150. const response = await fetch(url, requestConfig);
  151. if (response.headers.get("token_code") == -2 || response.headers.get("token_code") == -1) {
  152. // alert("当前账号已过期,请重新登录!");
  153. // window.alert=function(str){return;}
  154. Vue.prototype.$Message.config({
  155. top: 80,
  156. duration: 3
  157. });
  158. Vue.prototype.$Message.info("当前账号已过期,请重新登录!");
  159. Vue.prototype.$Message = function (str) {
  160. return;
  161. }
  162. setTimeout(function () {
  163. localStorage.clear();
  164. if (host.PROJECT && host.PROJECT == "xingfujiye") {
  165. window.location.href = "http://csms.cfldcn.com:5902/qpi/logoutFilter?returnUrl=" + Util.filterUrl(window.location.href);
  166. } else {
  167. location.reload();
  168. }
  169. return;
  170. }, 3000);
  171. } else if (response.headers.get("securitycode") && response.headers.get("securitycode") == 0) {
  172. //0.未通过; -1.不验证; 1.通过;
  173. Vue.prototype.$Message.config({
  174. top: 80,
  175. duration: 3
  176. });
  177. Vue.prototype.$Message.info("非法请求");
  178. setTimeout(function () {
  179. localStorage.clear();
  180. if (host.PROJECT && host.PROJECT == "xingfujiye") {
  181. window.location.href = "http://csms.cfldcn.com:5902/qpi/logoutFilter?returnUrl=" + Util.filterUrl(window.location.href);
  182. } else {
  183. location.reload();
  184. }
  185. return;
  186. }, 3000);
  187. } else {
  188. if (dataType && dataType === "XML") {
  189. const responseJson = await response.text();
  190. return responseJson
  191. } else {
  192. const responseJson = await response.json();
  193. if (responseJson.status == '401') {
  194. localStorage.clear();
  195. sessionStorage.clear();
  196. location.reload();
  197. }
  198. return responseJson
  199. }
  200. }
  201. } catch (error) {
  202. Vue.prototype.$Spin.hide();
  203. const responseJson = {
  204. errCode: 500,
  205. msg: "系统异常"
  206. };
  207. return responseJson;
  208. // throw new Error(error)
  209. }
  210. } else {
  211. return new Promise((resolve, reject) => {
  212. let requestObj;
  213. if (window.XMLHttpRequest) {
  214. requestObj = new XMLHttpRequest();
  215. } else {
  216. requestObj = new ActiveXObject;
  217. }
  218. let sendData = '';
  219. // if (type == 'POST') {
  220. // console.log(data)
  221. // Object.keys(data).forEach(key => {
  222. // sendData += key + '=' + data[key] + '&';
  223. // })
  224. // sendData = sendData.substr(0, sendData.lastIndexOf('&'));
  225. // }
  226. if ((type == 'POST' || type == 'PUT' || type == 'DELETE') && dataType != "JSON2" && dataType != "FORMDATA") {
  227. sendData = initData(data)
  228. } else if ((type == 'POST' || type == 'PUT' || type == 'DELETE') && dataType == "JSON2") {
  229. sendData = JSON.stringify(data)
  230. } else if ((type == 'POST') && dataType == "FORMDATA") {
  231. sendData = data
  232. }
  233. requestObj.open(type, url, true);
  234. if (dataType && dataType === "XML") {
  235. requestObj.setRequestHeader("Accept", "application/xml");
  236. requestObj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  237. } else if (dataType && dataType === "JSON2") {
  238. requestObj.setRequestHeader("Accept", "application/json");
  239. requestObj.setRequestHeader("Content-Type", "application/json");
  240. } else if (dataType && dataType === "FORMDATA") {
  241. requestObj.setRequestHeader("Accept", "application/json");
  242. requestObj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  243. requestObj.setRequestHeader("dataType", "json");
  244. requestObj.setRequestHeader("cache", false); //上传文件无需缓存
  245. requestObj.setRequestHeader("processData", false); //用于对data参数进行序列化处理 这里必须false
  246. requestObj.setRequestHeader("contentType", false); //必须
  247. }
  248. requestObj.setRequestHeader("sign", key_gen.encode(key_gen.handlerData(type == 'GET' ? url.substring(url.indexOf("?") + 1) : data)));
  249. if (localStorage.token != "" && typeof (localStorage.token) !== "undefined") {
  250. requestObj.setRequestHeader("token", localStorage.token);
  251. requestObj.setRequestHeader("client_token", localStorage.token);
  252. }
  253. if (localStorage.companyId != "" && typeof (localStorage.companyId) !== "undefined") {
  254. requestObj.setRequestHeader("companyId", localStorage.companyId);
  255. }
  256. if (localStorage.user_id != "" && typeof (localStorage.user_id) !== "undefined") {
  257. requestObj.setRequestHeader("user_id", localStorage.user_id);
  258. }
  259. requestObj.send(sendData);
  260. requestObj.onreadystatechange = () => {
  261. if (requestObj.readyState == 4) {
  262. if (requestObj.status == 200) {
  263. let obj = requestObj.response || requestObj.responseT
  264. if (typeof obj !== 'object' && obj.indexOf("<?xml") == -1) {
  265. obj = JSON.parse(obj);
  266. }
  267. resolve(obj)
  268. }
  269. }
  270. }
  271. })
  272. }
  273. }