http.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. "use strict";
  2. import axios from "axios";
  3. import bus from "./bus.js";
  4. import {router} from '../main'
  5. let store=null
  6. // 异步加载store模块 不异步加载的话,@/api/modules/oldApi.js的导入导出写法会有问题
  7. import('@/vuex/index.js')
  8. .then(module => {
  9. store=module.default
  10. })
  11. .catch(err => {
  12. console.error(err,'vuex加载错误');
  13. });
  14. axios.defaults.withCredentials = true;
  15. axios.defaults.timeout = 0;
  16. axios.interceptors.request.use(
  17. (config) => {
  18. // 请求拦截
  19. let auth = localStorage.getItem("auth");
  20. if (auth) {
  21. config.headers.Authorization = auth;
  22. }
  23. const uuid = localStorage.getItem("uuid") || "";
  24. config.headers.Uuid = uuid;
  25. config.headers.AccessToken = uuid + "--zheshiyigename";
  26. config.headers.Lang = localStorage.getItem("i18n") || 'zh';
  27. return config;
  28. },
  29. (error) => {
  30. return Promise.reject(error);
  31. }
  32. );
  33. axios.interceptors.response.use(
  34. (response) => {
  35. //响应拦截
  36. return response;
  37. },
  38. (error) => {
  39. return Promise.reject(error);
  40. }
  41. );
  42. function postData(val, url) {
  43. //处理请求数据
  44. return val;
  45. }
  46. function getData(val, url) {
  47. //处理请求数据
  48. return val;
  49. }
  50. function errorMsgShow(closableErrMsg,msg){
  51. if(closableErrMsg){
  52. let messageHint = bus.$message.error({
  53. message:msg,
  54. duration:0,
  55. showClose:true
  56. })
  57. store.mutations.PUSH_CLOSABLE_HINT(store.state,messageHint)
  58. }else{
  59. bus.$message.error(msg);
  60. }
  61. }
  62. let loginOutCount=0
  63. function checkStatus(response,closableErrMsg) {
  64. //处理响应数据
  65. if (response && response.status === 200) {
  66. // loading,如果http状态码正常,则直接返回数据
  67. let res = bus.$parseData(response);
  68. if (!res) {
  69. errorMsgShow(closableErrMsg,'服务器开了个小差')
  70. return false;
  71. } else if (res.Ret == 403) {
  72. errorMsgShow(closableErrMsg,res.Msg)
  73. } else if (res.Ret === 408) {
  74. if(loginOutCount===0){
  75. localStorage.setItem("loginTime", "")
  76. bus.$alert(res.Msg, "提示", {
  77. showClose: false,
  78. }).then(() => {
  79. loginOutCount=0
  80. router.replace('/login')
  81. // window.location.href = window.location.origin + '/login';
  82. });
  83. }
  84. loginOutCount++
  85. // localStorage.setItem("auth", "")
  86. }
  87. return res;
  88. } else {
  89. errorMsgShow(closableErrMsg,'网络异常')
  90. return false;
  91. }
  92. }
  93. function checkCode(res,closableErrMsg) {
  94. errorMsgShow(closableErrMsg,'网络异常')
  95. }
  96. function isFormData(obj) {
  97. return typeof obj === 'object' && obj instanceof FormData;
  98. }
  99. // 请求时间需要过长,取消限制
  100. const cancelTimeoutUrlPost = ["/cloud_disk/resource/upload"];
  101. export default {
  102. post(url, data) {
  103. //post请求方式
  104. let timeout = cancelTimeoutUrlPost.includes(url) ? 0 : 600000;
  105. // 自定义参数
  106. /**
  107. * closableErrMsg123 -- 错误提示需要时可关闭类型的
  108. */
  109. let closableErrMsg=false
  110. if(data){
  111. // 区分formData格式
  112. closableErrMsg = isFormData(data)?!!data.get('closableErrMsg123'):!!data.closableErrMsg123
  113. isFormData(data)?data.delete('closableErrMsg123'):(data.closableErrMsg123=undefined)
  114. }
  115. return axios({
  116. method: "post",
  117. url: url,
  118. baseURL: process.env.VUE_APP_API_ROOT,
  119. data: postData(data, url),
  120. timeout,
  121. headers: { "Content-Type": "application/json; charset=utf-8" },
  122. })
  123. .then((response) => {
  124. return checkStatus(response,closableErrMsg);
  125. })
  126. .catch((res) => {
  127. return checkCode(res,closableErrMsg);
  128. });
  129. },
  130. get(url, data, responseType = "json") {
  131. // 自定义参数
  132. /**
  133. * closableErrMsg123 -- 错误提示需要时可关闭类型的
  134. */
  135. let closableErrMsg=false
  136. if(data){
  137. closableErrMsg = !!data.closableErrMsg123
  138. data.closableErrMsg123=undefined
  139. }
  140. //get请求方式
  141. return axios({
  142. method: "get",
  143. baseURL: process.env.VUE_APP_API_ROOT,
  144. url: url,
  145. params: getData(data, url),
  146. timeout:600000,
  147. headers: {
  148. "Content-type": "application/x-www-form-urlencoded; charset=utf-8",
  149. },
  150. responseType: responseType,
  151. transformRequest: [
  152. function (data) {
  153. let ret = "";
  154. for (let it in data) {
  155. ret +=
  156. encodeURIComponent(it) + "=" + encodeURIComponent(data[it]) + "&";
  157. }
  158. return ret;
  159. },
  160. ],
  161. })
  162. .then((response) => {
  163. if(responseType==='blob'){
  164. return response
  165. }
  166. return checkStatus(response,closableErrMsg);
  167. })
  168. .catch((res) => {
  169. return checkCode(res,closableErrMsg);
  170. });
  171. },
  172. Base64,
  173. dateFormatter,
  174. getTotalMonth,
  175. Decrypt,
  176. Encrypt,
  177. isMobileNo,
  178. };
  179. //解密方法
  180. function Decrypt(word) {
  181. let encryptedHexStr = CryptoJS.enc.Hex.parse(word);
  182. let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
  183. let decrypt = CryptoJS.AES.decrypt(srcs, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
  184. let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
  185. return decryptedStr.toString();
  186. }
  187. //加密方法
  188. function Encrypt(word) {
  189. let srcs = CryptoJS.enc.Utf8.parse(word);
  190. let encrypted = CryptoJS.AES.encrypt(srcs, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
  191. return encrypted.ciphertext.toString().toUpperCase();
  192. }
  193. function isMobileNo(account) {
  194. // 手机号正则
  195. var isChinaMobile = new RegExp(
  196. "(^1(3[4-9]|4[78]|5[0-27-9]|7[28]|8[2-478]|98)\\d{8}$)"
  197. ); // 中国移动
  198. // 手机段:134,135,136,137,138,139,147,148[卫星通信],150,151,152,157,158,159,172,178,182,183,184,187,188,198
  199. var isChinaUnicom = new RegExp(
  200. "(^1(3[0-2]|4[56]|5[56]|66|7[156]|8[56])\\d{8}$)"
  201. ); // 中国联通
  202. // 手机段:130,131,132,145,146[卫星通信],155,156,166,171,175,176,185,186
  203. var isChinaTelcom = new RegExp("(^1(33|49|53|7[347]|8[019]|99)\\d{8}$)"); // 中国电信
  204. // 手机段:133,149,153,173,174,177,180,181,189,199
  205. var isOtherTelphone = new RegExp("(^170\\d{8}$)");
  206. // 虚拟运营商170号段
  207. if (isChinaMobile.test(account)) {
  208. return true;
  209. } else if (isChinaUnicom.test(account)) {
  210. return true;
  211. } else if (isChinaTelcom.test(account)) {
  212. return true;
  213. } else return isOtherTelphone.test(account);
  214. }
  215. function Base64() {
  216. // private property
  217. var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  218. // public method for encoding
  219. this.encode = function (input) {
  220. var output = "";
  221. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  222. var i = 0;
  223. input = this._utf8_encode(input);
  224. while (i < input.length) {
  225. chr1 = input.charCodeAt(i++);
  226. chr2 = input.charCodeAt(i++);
  227. chr3 = input.charCodeAt(i++);
  228. enc1 = chr1 >> 2;
  229. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  230. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  231. enc4 = chr3 & 63;
  232. if (isNaN(chr2)) {
  233. enc3 = enc4 = 64;
  234. } else if (isNaN(chr3)) {
  235. enc4 = 64;
  236. }
  237. output = output +
  238. _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
  239. _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
  240. }
  241. return output;
  242. }
  243. // public method for decoding
  244. this.decode = function (input) {
  245. var output = "";
  246. var chr1, chr2, chr3;
  247. var enc1, enc2, enc3, enc4;
  248. var i = 0;
  249. input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  250. while (i < input.length) {
  251. enc1 = _keyStr.indexOf(input.charAt(i++));
  252. enc2 = _keyStr.indexOf(input.charAt(i++));
  253. enc3 = _keyStr.indexOf(input.charAt(i++));
  254. enc4 = _keyStr.indexOf(input.charAt(i++));
  255. chr1 = (enc1 << 2) | (enc2 >> 4);
  256. chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
  257. chr3 = ((enc3 & 3) << 6) | enc4;
  258. output = output + String.fromCharCode(chr1);
  259. if (enc3 != 64) {
  260. output = output + String.fromCharCode(chr2);
  261. }
  262. if (enc4 != 64) {
  263. output = output + String.fromCharCode(chr3);
  264. }
  265. }
  266. output = this._utf8_decode(output);
  267. return output;
  268. }
  269. // private method for UTF-8 encoding
  270. this._utf8_encode = function (string) {
  271. string = string.replace(/\r\n/g, "\n");
  272. var utftext = "";
  273. for (var n = 0; n < string.length; n++) {
  274. var c = string.charCodeAt(n);
  275. if (c < 128) {
  276. utftext += String.fromCharCode(c);
  277. } else if ((c > 127) && (c < 2048)) {
  278. utftext += String.fromCharCode((c >> 6) | 192);
  279. utftext += String.fromCharCode((c & 63) | 128);
  280. } else {
  281. utftext += String.fromCharCode((c >> 12) | 224);
  282. utftext += String.fromCharCode(((c >> 6) & 63) | 128);
  283. utftext += String.fromCharCode((c & 63) | 128);
  284. }
  285. }
  286. return utftext;
  287. }
  288. // private method for UTF-8 decoding
  289. this._utf8_decode = function (utftext) {
  290. var string = "";
  291. var i = 0;
  292. var c = 0;
  293. var c1 = 0;
  294. var c2 = 0;
  295. while (i < utftext.length) {
  296. c = utftext.charCodeAt(i);
  297. if (c < 128) {
  298. string += String.fromCharCode(c);
  299. i++;
  300. } else if ((c > 191) && (c < 224)) {
  301. c2 = utftext.charCodeAt(i + 1);
  302. string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
  303. i += 2;
  304. } else {
  305. c2 = utftext.charCodeAt(i + 1);
  306. var c3 = utftext.charCodeAt(i + 2);
  307. string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
  308. i += 3;
  309. }
  310. }
  311. return string;
  312. }
  313. }
  314. function dateFormatter(str) {
  315. //默认返回yyyy-MM-dd HH-mm-ss
  316. var hasTime = arguments[1] != false ? true : false; //可传第二个参数false,返回yyyy-MM-dd
  317. var hasType = arguments[2]; //可传第三个参数,tru 返回yyyy年MM月dd日
  318. var dateStr = String(str);
  319. if (!(dateStr.indexOf("-") > -1 && dateStr.indexOf("T") > -1)) {
  320. dateStr = dateStr.replace(/\-/g, "/");
  321. }
  322. var d = new Date(dateStr);
  323. var year = d.getFullYear();
  324. var month =
  325. d.getMonth() + 1 < 10 ? "0" + (d.getMonth() + 1) : d.getMonth() + 1;
  326. var day = d.getDate() < 10 ? "0" + d.getDate() : d.getDate();
  327. var hour = d.getHours() < 10 ? "0" + d.getHours() : d.getHours();
  328. var minute = d.getMinutes() < 10 ? "0" + d.getMinutes() : d.getMinutes();
  329. var second = d.getSeconds() < 10 ? "0" + d.getSeconds() : d.getSeconds();
  330. if (hasTime) {
  331. if (hasType) {
  332. return `${month}月${day}日 ${hour}时${minute}分${second}秒`;
  333. }
  334. return (
  335. [year, month, day].join(".") + " " + [hour, minute, second].join(":")
  336. );
  337. } else {
  338. if (hasType) {
  339. return `${month}月${day}日`;
  340. }
  341. return [year, month, day].join(".");
  342. }
  343. }
  344. function getTotalMonth(date, hasTime = false) {
  345. //默认返回 [yyyy-MM-01,yyyy-MM-dd] 整月时间
  346. let newDate = new Date(date);
  347. let year = newDate.getFullYear();
  348. let month =
  349. newDate.getMonth() + 1 < 10
  350. ? "0" + (newDate.getMonth() + 1)
  351. : newDate.getMonth() + 1;
  352. var hour =
  353. newDate.getHours() < 10 ? "0" + newDate.getHours() : newDate.getHours();
  354. var minute =
  355. newDate.getMinutes() < 10
  356. ? "0" + newDate.getMinutes()
  357. : newDate.getMinutes();
  358. var second =
  359. newDate.getSeconds() < 10
  360. ? "0" + newDate.getSeconds()
  361. : newDate.getSeconds();
  362. let timestamp =
  363. new Date(`${year}/${newDate.getMonth() + 2}/01`).getTime() -
  364. 24 * 60 * 60 * 1000;
  365. if (hasTime) {
  366. return [
  367. `${year}-${month}-01 ${hour}:${minute}:${second}`,
  368. dateFormatter(timestamp, true),
  369. ];
  370. } else {
  371. return [`${year}-${month}-01`, dateFormatter(timestamp, false)];
  372. }
  373. }
  374. export async function downloadFileByUrl(dataUrl) {
  375. return (await fetch(dataUrl)).blob();
  376. }