fetch.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. import './../static/encry.min' // 接口参数加密
  2. import util from '@/util/util'
  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. formMap.append(key, params[key]);
  10. }
  11. return formMap;
  12. } else {
  13. return params;
  14. }
  15. }
  16. function tokenCheck(status) {
  17. if (status === 401) {
  18. // store.commit('logout', this);
  19. // store.commit('clearOpenedSubmenu');
  20. // store.commit('clearAllTags');
  21. // router.push({
  22. // name: 'login',
  23. // props: {
  24. // timeout: true
  25. // },
  26. // query: {
  27. // isTokenInValid: true
  28. // }
  29. // });
  30. }
  31. return false;
  32. }
  33. function showTokenInvalid(val) {
  34. let tips = '未知token错误'
  35. switch (val) {
  36. case -1:
  37. tips = 'token为空'
  38. break;
  39. case -2:
  40. tips = 'token无效或过期'
  41. break;
  42. default:
  43. break;
  44. }
  45. alert(tips)
  46. }
  47. function showParamCheck(val) {
  48. let tips = '参数校验错误'
  49. switch (val) {
  50. case -2:
  51. tips = '参数校验失败'
  52. break;
  53. case -3:
  54. tips = '参数校验失败,服务器异常'
  55. break;
  56. default:
  57. break;
  58. }
  59. alert(tips)
  60. }
  61. export default async (url = '', baseUrl = '', data = {}, dataType = 'JSON', type = 'GET', requestType = 'JSON', pathArr = [], method = 'fetch') => {
  62. type = type.toUpperCase();
  63. // 拼接userid
  64. // data.userId = localStorage.userId;
  65. // 清除空参数
  66. data = util.filter_param(data);
  67. if (process.env.NODE_ENV === 'production') {
  68. let hostConfig = process.env.hostConfig
  69. if (baseUrl) {
  70. switch (baseUrl) {
  71. case "/crm400":
  72. baseUrl = process.env.findAddr(hostConfig, 'crm400');
  73. break;
  74. case "/walter":
  75. baseUrl = process.env.findAddr(hostConfig, 'walter');
  76. break;
  77. case "/club":
  78. baseUrl = process.env.findAddr(hostConfig, 'club');
  79. break;
  80. case "/activity":
  81. baseUrl = process.env.findAddr(hostConfig, 'activity');
  82. break;
  83. case "/steward":
  84. baseUrl = process.env.findAddr(hostConfig, 'steward');
  85. break;
  86. case "/houserkeep":
  87. baseUrl = process.env.findAddr(hostConfig, 'houserkeep');
  88. break;
  89. case '/question': //调查问卷
  90. baseUrl = process.env.findAddr(hostConfig, 'question');
  91. break;
  92. case '/article': //文章
  93. baseUrl = process.env.findAddr(hostConfig, 'article');
  94. break;
  95. case '/charge': //收费系统
  96. baseUrl = process.env.findAddr(hostConfig, 'charge');
  97. break;
  98. case '/activiti': // 用餐预定、会议室预定
  99. baseUrl = process.env.findAddr(hostConfig, 'activiti');
  100. break;
  101. case '/decorationManage': // 装修申请
  102. baseUrl = process.env.findAddr(hostConfig, 'decorationManage');
  103. break;
  104. case '/itemPassport': // 物品放行
  105. baseUrl = process.env.findAddr(hostConfig, 'itemPassport');
  106. break;
  107. case '/itemHouse': // 物品放行
  108. baseUrl = process.env.findAddr(hostConfig, 'itemHouse');
  109. break;
  110. case '/datashow': //深交所 - 管理视图
  111. baseUrl = process.env.findAddr(hostConfig, 'datashow');
  112. break;
  113. case '/warning': //深交所 - 预警
  114. baseUrl = process.env.findAddr(hostConfig, 'warning');
  115. break;
  116. case '/groupcontrol': //深交所 - 会议管理
  117. baseUrl = process.env.findAddr(hostConfig, 'groupcontrol');
  118. break;
  119. case '/energy-charging': //深交所 - 水电气表查询
  120. baseUrl = process.env.findAddr(hostConfig, 'energyCharging');
  121. break;
  122. case '/wuyecrm': //深交所 - 水电气表查询
  123. baseUrl = process.env.findAddr(hostConfig, 'wuyecrm');
  124. break;
  125. case '/qpi': //内控
  126. baseUrl = process.env.findAddr(hostConfig, 'qpi');
  127. break;
  128. case '/leasing': //内控
  129. baseUrl = process.env.findAddr(hostConfig, 'leasing');
  130. break;
  131. case '/neikong': //内控
  132. baseUrl = process.env.findAddr(hostConfig, 'neikong');
  133. break;
  134. case '/device': //设备预警
  135. baseUrl = process.env.findAddr(hostConfig, 'device');
  136. break;
  137. default:
  138. baseUrl = "";
  139. }
  140. }
  141. }
  142. url = baseUrl + url;
  143. if (pathArr && pathArr.length > 0) {
  144. url += "/" + pathArr.join("/");
  145. }
  146. if (type === 'GET') {
  147. let dataStr = ''; //数据拼接字符串
  148. Object.keys(data).forEach(key => {
  149. dataStr += key + '=' + data[key] + '&';
  150. })
  151. if (dataStr !== '') {
  152. dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
  153. url = url + '?' + dataStr + '&_t=' + new Date().getTime();
  154. } else {
  155. url = url + '?_t=' + new Date().getTime();
  156. }
  157. }
  158. if (window.fetch && method === 'fetch') {
  159. var header_content = {
  160. 'Accept': 'application/json',
  161. 'Content-Type': 'application/x-www-form-urlencoded',
  162. 'x-user-header': localStorage.user_account ? localStorage.user_account : '',
  163. 'x-userId-header': localStorage.user_id ? localStorage.user_id : '',
  164. 'x-userAccount-header': localStorage.userAccount ? encodeURI(localStorage.userAccount) : '',
  165. 'x-userName-header': localStorage.userName ? encodeURI(localStorage.userName) : '',
  166. 'x-companyId-header': localStorage.companyId ? localStorage.companyId : '',
  167. };
  168. if (dataType && dataType === "XML") {
  169. header_content = {
  170. 'Accept': 'application/xml',
  171. 'Content-Type': 'application/x-www-form-urlencoded',
  172. 'x-user-header': localStorage.user_account ? localStorage.user_account : '',
  173. 'x-userId-header': localStorage.user_id ? localStorage.user_id : '',
  174. 'x-userAccount-header': localStorage.userAccount ? encodeURI(localStorage.userAccount) : '',
  175. 'x-userName-header': localStorage.userName ? encodeURI(localStorage.userName) : '',
  176. 'x-companyId-header': localStorage.companyId ? localStorage.companyId : '',
  177. };
  178. } else if (requestType === "JSON") {
  179. if (type === 'POST') {
  180. header_content = {
  181. 'Accept': 'application/json',
  182. 'Content-Type': 'application/json',
  183. 'x-user-header': localStorage.user_account ? localStorage.user_account : '',
  184. 'x-userId-header': localStorage.user_id ? localStorage.user_id : '',
  185. 'x-userAccount-header': localStorage.userAccount ? encodeURI(localStorage.userAccount) : '',
  186. 'x-userName-header': localStorage.userName ? encodeURI(localStorage.userName) : '',
  187. 'x-companyId-header': localStorage.companyId ? localStorage.companyId : '',
  188. };
  189. }
  190. } else if (requestType === "FORMDATA") {
  191. header_content = {
  192. 'Accept': 'application/json',
  193. 'Content-Type': 'application/x-www-form-urlencoded',
  194. 'Authorization': "Basic ZWJlaTplYmVp",
  195. 'x-user-header': localStorage.user_account ? localStorage.user_account : '',
  196. 'x-userId-header': localStorage.user_id ? localStorage.user_id : '',
  197. 'x-userAccount-header': localStorage.userAccount ? encodeURI(localStorage.userAccount) : '',
  198. 'x-userName-header': localStorage.userName ? encodeURI(localStorage.userName) : '',
  199. 'x-companyId-header': localStorage.companyId ? localStorage.companyId : '',
  200. };
  201. }
  202. if (localStorage.token && requestType === "JSON") {
  203. header_content.Authorization = (localStorage.tokenType === "bearer" ? "Bearer " : "") + localStorage.token;
  204. } else {
  205. tokenCheck(402);
  206. }
  207. header_content.token = localStorage.getItem('token') || ""
  208. header_content.sign = key_gen.encode(key_gen.handlerData(type === 'GET' ? url.substring(url.indexOf("?") + 1) : data));
  209. try {
  210. var useraccount = localStorage.getItem('userAccount');
  211. if (useraccount) {
  212. header_content.useraccount = encodeURI(useraccount);
  213. }
  214. var username = localStorage.getItem('fullName')
  215. if (username) {
  216. header_content.username = encodeURI(username);
  217. }
  218. var projectname = JSON.parse(localStorage.getItem("currProject")).projectName;
  219. if (projectname) {
  220. header_content.projectname = encodeURI(projectname);
  221. }
  222. } catch (e) {
  223. console.log(JSON.stringify(e));
  224. }
  225. let requestConfig = {
  226. // credentials: 'include',
  227. method: type,
  228. headers: header_content,
  229. mode: "cors",
  230. cache: "no-cache"
  231. };
  232. if (type === 'POST') {
  233. if (requestType === "FORMDATA") {
  234. Object.defineProperty(requestConfig, 'body', {
  235. value: initData(data)
  236. })
  237. } else if (requestType === "JSON") {
  238. Object.defineProperty(requestConfig, 'body', {
  239. value: JSON.stringify(data)
  240. })
  241. }
  242. }
  243. try {
  244. const response = await fetch(url, requestConfig);
  245. if (dataType && dataType === "XML") {
  246. const responseJson = await response.text();
  247. // responseJson.interfacePath = process.env.NODE_ENV === 'development' ? url : '';
  248. // tokenCheck(responseJson.status);
  249. return responseJson
  250. } else {
  251. const responseJson = await response.json();
  252. responseJson.errCode = 200;
  253. responseJson.interfacePath = process.env.NODE_ENV === 'development' ? url : '';
  254. // token_code: -1:token为空,-2:token:无效或者过期
  255. if (responseJson.token_code === -1 || responseJson.token_code === -2) {
  256. if (util.isWeixin()) {
  257. showTokenInvalid(responseJson.token_code)
  258. } else {
  259. EbeiPlugins.showTokenInvalidAlert()
  260. }
  261. } else if (responseJson.code === -2 || responseJson.code === -3) {
  262. //code: -2:参数校验失败, -3: 服务器异常
  263. if (util.isWeixin()) {
  264. showParamCheck(responseJson.token_code)
  265. } else {
  266. EbeiPlugins.showParamInvalidAlert(responseJson.code)
  267. }
  268. }
  269. return responseJson
  270. }
  271. } catch (error) {
  272. const responseJson = {
  273. errCode: 500,
  274. msg: "系统异常"
  275. };
  276. return responseJson;
  277. }
  278. } else {
  279. return new Promise((resolve, reject) => {
  280. let requestObj;
  281. if (window.XMLHttpRequest) {
  282. requestObj = new XMLHttpRequest();
  283. } else {
  284. requestObj = new ActiveXObject;
  285. }
  286. let sendData = '';
  287. if (type === 'POST') {
  288. if (requestType === "FORMDATA") {
  289. sendData = initData(data);
  290. } else if (requestType === "JSON") {
  291. sendData = JSON.stringify(data);
  292. }
  293. }
  294. requestObj.open(type, url, true);
  295. if (requestType === "JSON") {
  296. if (type === 'GET') {
  297. requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  298. } else if (type === 'POST') {
  299. requestObj.setRequestHeader("Content-type", "application/json");
  300. }
  301. } else {
  302. requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  303. }
  304. requestObj.setRequestHeader("token", localStorage.getItem('token') || "");
  305. requestObj.setRequestHeader("sign", key_gen.encode(key_gen.handlerData(type == 'GET' ? url.substring(url.indexOf("?") + 1) : data)));
  306. try {
  307. var useraccount = localStorage.getItem('userAccount');
  308. if (useraccount) {
  309. requestObj.setRequestHeader("useraccount", encodeURI(useraccount));
  310. }
  311. var username = localStorage.getItem('fullName')
  312. if (username) {
  313. requestObj.setRequestHeader("username", encodeURI(username));
  314. }
  315. var projectname = JSON.parse(localStorage.getItem("currProject")).projectName;
  316. if (projectname) {
  317. requestObj.setRequestHeader("projectname", encodeURI(projectname));
  318. }
  319. } catch (e) {
  320. console.log(JSON.stringify(e));
  321. }
  322. requestObj.send(sendData);
  323. requestObj.onreadystatechange = () => {
  324. if (requestObj.readyState == 4) {
  325. if (requestObj.status == 200) {
  326. let obj = requestObj.response
  327. if (typeof obj !== 'object' && obj.indexOf("<?xml") == -1) {
  328. obj = JSON.parse(obj);
  329. }
  330. obj.interfacePath = process.env.NODE_ENV === 'development' ? url : '';
  331. // token_code: -1:token为空,-2:token:无效或者过期
  332. if (obj.token_code === -1 || obj.token_code === -2) {
  333. if (util.isWeixin()) {
  334. showTokenInvalid(obj.token_code)
  335. } else {
  336. EbeiPlugins.showTokenInvalidAlert()
  337. }
  338. } else if (obj.code === -2 || obj.code === -3) {
  339. //code: -2:参数校验失败, -3: 服务器异常
  340. if (util.isWeixin()) {
  341. showParamCheck(obj.code)
  342. } else {
  343. EbeiPlugins.showParamInvalidAlert(obj.code)
  344. }
  345. }
  346. // tokenCheck(obj.status);
  347. resolve(obj)
  348. } else {
  349. reject(requestObj)
  350. }
  351. }
  352. }
  353. })
  354. }
  355. }