mhttp.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. /**
  2. * 管理后台http客户端,避免冲突导出为mhttp
  3. */
  4. layui.define(['jquery', 'layer', 'http', 'toast', 'madmin'], function (exports) {
  5. "use strict";
  6. var $ = layui.jquery;
  7. var layer = layui.layer;
  8. var toast = layui.toast;
  9. var admin = layui.madmin;
  10. var http = {};
  11. http.ajax = function (userOptions, innerData) {
  12. var objOptions = {};
  13. if (userOptions && typeof(userOptions) == 'string') {
  14. // 参数是字符串,直接拼接选项url.
  15. objOptions.url = userOptions;
  16. userOptions = objOptions;
  17. }
  18. userOptions = userOptions || {};
  19. if (userOptions) {
  20. if (typeof(userOptions.url) != 'undefined') {
  21. var originUrl = userOptions.url;
  22. var config = admin.getConfig();
  23. var baseUrl = window._CONFIG_.sysconfig.apiServerBaseUrl;
  24. var reg1 = /^(http:|https:)/;
  25. if (!reg1.test(originUrl)) {
  26. userOptions.url = baseUrl.rtrim('/') + '/' + userOptions.url.ltrim('/');
  27. }
  28. var urlConcat = '&';
  29. if (userOptions.url.lastIndexOf('?') == -1) {
  30. // 没有找到.
  31. urlConcat = '?';
  32. }
  33. // 追加刷新随机hash.
  34. userOptions.url += urlConcat + '_fresh=' + Math.random() * 100000;
  35. // 相对协议.
  36. userOptions.url = slashesUrl(userOptions.url);
  37. }
  38. }
  39. if (innerData) {
  40. userOptions.data = JSON.stringify({
  41. "data" : innerData,
  42. "handshake": ''
  43. });
  44. }
  45. var originInnerData = userOptions.data ?? {};
  46. userOptions.data = JSON.stringify({
  47. "data" : originInnerData,
  48. "handshake": ''
  49. });
  50. var options = $.extend(true, {}, http.ajax.defaultOpts, userOptions);
  51. var oldBeforeSendOption = options.beforeSend;
  52. options.beforeSend = function (xhr) {
  53. if (oldBeforeSendOption) {
  54. oldBeforeSendOption(xhr);
  55. }
  56. xhr.setRequestHeader("Pragma", "no-cache");
  57. xhr.setRequestHeader("Cache-Control", "no-cache");
  58. xhr.setRequestHeader("Expires", "Sat, 01 Jan 2000 00:00:00 GMT");
  59. };
  60. options.success = undefined;
  61. options.error = undefined;
  62. return $.Deferred(function ($dfd) {
  63. $.ajax(options)
  64. .done(function (data, textStatus, jqXHR) {
  65. if (data.hasOwnProperty('code') && data.hasOwnProperty('handshake')) {
  66. // 盲写,还没对接接口测试.
  67. var intCode = parseInt(data.code);
  68. var redirectUrl = window.rootUrl + '/login.html';
  69. if (intCode == 403) {
  70. http.ajax.showErrorAndRedirectUrl(http.ajax.defaultError403, redirectUrl);
  71. } else if (intCode == 401) {
  72. // 仅仅是过期了,这里可以有其他逻辑补偿.
  73. // 暂时跳到登陆页面
  74. // refreshToken();
  75. http.ajax.showErrorAndRedirectUrlByYes(http.ajax.defaultError401, redirectUrl);
  76. }
  77. }
  78. $dfd.resolve(data);
  79. userOptions.success && userOptions.success(data);
  80. })
  81. .fail(function (jqXHR) {
  82. http.ajax.handleErrorResponse(jqXHR, userOptions, $dfd);
  83. });
  84. });
  85. }
  86. $.extend(http.ajax, {
  87. defaultOpts: {
  88. dataType: 'json',
  89. type: 'POST',
  90. contentType: 'application/json',
  91. headers: {
  92. // 'X-Requested-With': 'XMLHttpRequest'
  93. }
  94. },
  95. defaultError: {
  96. message: '发生错误!',
  97. details: '未知错误.'
  98. },
  99. defaultError401: {
  100. message: '授权过期',
  101. details: '请重新登陆.'
  102. },
  103. defaultError403: {
  104. message: '认证失效!',
  105. details: '无权操作.'
  106. },
  107. defaultError404: {
  108. message: '资源未找到',
  109. details: '服务器上没找到资源.'
  110. },
  111. logError: function (error) {
  112. console.log(error);
  113. },
  114. showError: function (error) {
  115. if (error.details) {
  116. return layer.alert(error.details, {
  117. title: error.message,
  118. icon: 2,
  119. closeBtn: 0
  120. });
  121. } else {
  122. return layer.alert(http.ajax.defaultError.details, {
  123. title: error.message || http.ajax.defaultError.message,
  124. icon: 2,
  125. closeBtn: 0
  126. });
  127. }
  128. },
  129. showErrorAndRedirectUrlByYes: function (error, targetUrl) {
  130. return layer.alert(http.ajax.defaultError401.details, {
  131. title: http.ajax.defaultError401.message,
  132. icon: 2,
  133. closeBtn: 0
  134. }
  135. ,
  136. function (index) {
  137. http.ajax.handleTargetUrl(targetUrl)
  138. layer.close(index);
  139. }
  140. );
  141. },
  142. showErrorAndRedirectUrl: function (error, targetUrl) {
  143. if (error.details) {
  144. return layer.alert(error.details, {
  145. title: error.message,
  146. icon: 2,
  147. closeBtn: 0
  148. ,
  149. end: http.ajax.handleTargetUrl(targetUrl)
  150. }
  151. // ,
  152. // function (index) {
  153. // http.ajax.handleTargetUrl(targetUrl)
  154. // layer.close(index);
  155. // }
  156. );
  157. } else {
  158. return layer.alert(http.ajax.defaultError.details, {
  159. title: error.message || http.ajax.defaultError.message,
  160. icon: 2,
  161. closeBtn: 0
  162. ,
  163. end: http.ajax.handleTargetUrl(targetUrl)
  164. }
  165. // ,
  166. // function (index) {
  167. // http.ajax.handleTargetUrl(targetUrl)
  168. // layer.close(index);
  169. // }
  170. );
  171. }
  172. },
  173. handleTargetUrl: function (targetUrl) {
  174. if (!targetUrl) {
  175. parent.location.href = http.appPath;
  176. } else {
  177. parent.location.href = targetUrl;
  178. }
  179. },
  180. handleErrorResponse: function (jqXHR, userOptions, $dfd) {
  181. if (userOptions.customHandleError !== false) {
  182. switch (jqXHR.status) {
  183. case 401:
  184. http.ajax.showErrorAndRedirectUrl(http.ajax.defaultError401, http.appPath);
  185. break;
  186. case 403:
  187. http.ajax.showError(http.ajax.defaultError403);
  188. break;
  189. case 404:
  190. http.ajax.showError(http.ajax.defaultError404);
  191. break;
  192. default:
  193. http.ajax.showError(http.ajax.defaultError);
  194. break;
  195. }
  196. }
  197. $dfd.reject.apply(this, arguments);
  198. userOptions.error && userOptions.error.apply(this, arguments);
  199. },
  200. ajaxSendHandler: function (event, request, settings) {
  201. var token = http.ajax.getToken();
  202. if (!token) {
  203. return;
  204. }
  205. if (!settings.headers || settings.headers[http.ajax.tokenHeaderName] === undefined) {
  206. request.setRequestHeader(http.ajax.tokenHeaderName, token);
  207. }
  208. },
  209. setToken: function (token) {
  210. localStorage.setItem(http.ajax.tokenCookieName, token);
  211. },
  212. delToken: function () {
  213. localStorage.removeItem(http.ajax.tokenCookieName);
  214. },
  215. getToken: function () {
  216. return localStorage.getItem(http.ajax.tokenCookieName);
  217. },
  218. tokenCookieName :'XSRF-TOKEN',
  219. tokenHeaderName : 'AUTH-TOKEN',
  220. getCookieValue: function (key) {
  221. var equalities = document.cookie.split('; ');
  222. for (var i = 0; i < equalities.length; i++) {
  223. if (!equalities[i]) {
  224. continue;
  225. }
  226. var splitted = equalities[i].split('=');
  227. if (splitted.length != 2) {
  228. continue;
  229. }
  230. if (decodeURIComponent(splitted[0]) === key) {
  231. return decodeURIComponent(splitted[1] || '');
  232. }
  233. }
  234. return null;
  235. }
  236. });
  237. $(document).ajaxSend(function (event, request, settings) {
  238. return http.ajax.ajaxSendHandler(event, request, settings);
  239. });
  240. exports('mhttp', http);
  241. });