| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275 |
- /**
- * 管理后台http客户端,避免冲突导出为mhttp
- */
- layui.define(['jquery', 'layer', 'http', 'toast', 'madmin'], function (exports) {
- "use strict";
- var $ = layui.jquery;
- var layer = layui.layer;
- var toast = layui.toast;
- var admin = layui.madmin;
- var http = {};
- http.ajax = function (userOptions, innerData) {
- var objOptions = {};
- if (userOptions && typeof(userOptions) == 'string') {
- // 参数是字符串,直接拼接选项url.
- objOptions.url = userOptions;
- userOptions = objOptions;
- }
- userOptions = userOptions || {};
- if (userOptions) {
- if (typeof(userOptions.url) != 'undefined') {
- var originUrl = userOptions.url;
- var config = admin.getConfig();
- var baseUrl = window._CONFIG_.sysconfig.apiServerBaseUrl;
- var reg1 = /^(http:|https:)/;
- if (!reg1.test(originUrl)) {
- userOptions.url = baseUrl.rtrim('/') + '/' + userOptions.url.ltrim('/');
- }
- var urlConcat = '&';
- if (userOptions.url.lastIndexOf('?') == -1) {
- // 没有找到.
- urlConcat = '?';
- }
-
- // 追加刷新随机hash.
- userOptions.url += urlConcat + '_fresh=' + Math.random() * 100000;
- // 相对协议.
- userOptions.url = slashesUrl(userOptions.url);
- }
- }
- if (innerData) {
- userOptions.data = JSON.stringify({
- "data" : innerData,
- "handshake": ''
- });
- }
- var originInnerData = userOptions.data ?? {};
- userOptions.data = JSON.stringify({
- "data" : originInnerData,
- "handshake": ''
- });
- var options = $.extend(true, {}, http.ajax.defaultOpts, userOptions);
- var oldBeforeSendOption = options.beforeSend;
- options.beforeSend = function (xhr) {
- if (oldBeforeSendOption) {
- oldBeforeSendOption(xhr);
- }
- xhr.setRequestHeader("Pragma", "no-cache");
- xhr.setRequestHeader("Cache-Control", "no-cache");
- xhr.setRequestHeader("Expires", "Sat, 01 Jan 2000 00:00:00 GMT");
- };
- options.success = undefined;
- options.error = undefined;
- return $.Deferred(function ($dfd) {
- $.ajax(options)
- .done(function (data, textStatus, jqXHR) {
- if (data.hasOwnProperty('code') && data.hasOwnProperty('handshake')) {
- // 盲写,还没对接接口测试.
- var intCode = parseInt(data.code);
- var redirectUrl = window.rootUrl + '/login.html';
- if (intCode == 403) {
- http.ajax.showErrorAndRedirectUrl(http.ajax.defaultError403, redirectUrl);
- } else if (intCode == 401) {
- // 仅仅是过期了,这里可以有其他逻辑补偿.
- // 暂时跳到登陆页面
- // refreshToken();
- http.ajax.showErrorAndRedirectUrlByYes(http.ajax.defaultError401, redirectUrl);
- }
- }
- $dfd.resolve(data);
- userOptions.success && userOptions.success(data);
- })
- .fail(function (jqXHR) {
- http.ajax.handleErrorResponse(jqXHR, userOptions, $dfd);
- });
- });
- }
- $.extend(http.ajax, {
- defaultOpts: {
- dataType: 'json',
- type: 'POST',
- contentType: 'application/json',
- headers: {
- // 'X-Requested-With': 'XMLHttpRequest'
- }
- },
- defaultError: {
- message: '发生错误!',
- details: '未知错误.'
- },
- defaultError401: {
- message: '授权过期',
- details: '请重新登陆.'
- },
- defaultError403: {
- message: '认证失效!',
- details: '无权操作.'
- },
- defaultError404: {
- message: '资源未找到',
- details: '服务器上没找到资源.'
- },
- logError: function (error) {
- console.log(error);
- },
- showError: function (error) {
- if (error.details) {
- return layer.alert(error.details, {
- title: error.message,
- icon: 2,
- closeBtn: 0
- });
- } else {
- return layer.alert(http.ajax.defaultError.details, {
- title: error.message || http.ajax.defaultError.message,
- icon: 2,
- closeBtn: 0
- });
- }
- },
- showErrorAndRedirectUrlByYes: function (error, targetUrl) {
- return layer.alert(http.ajax.defaultError401.details, {
- title: http.ajax.defaultError401.message,
- icon: 2,
- closeBtn: 0
- }
- ,
- function (index) {
- http.ajax.handleTargetUrl(targetUrl)
- layer.close(index);
- }
- );
- },
- showErrorAndRedirectUrl: function (error, targetUrl) {
- if (error.details) {
- return layer.alert(error.details, {
- title: error.message,
- icon: 2,
- closeBtn: 0
- ,
- end: http.ajax.handleTargetUrl(targetUrl)
- }
- // ,
- // function (index) {
- // http.ajax.handleTargetUrl(targetUrl)
- // layer.close(index);
- // }
- );
- } else {
- return layer.alert(http.ajax.defaultError.details, {
- title: error.message || http.ajax.defaultError.message,
- icon: 2,
- closeBtn: 0
- ,
- end: http.ajax.handleTargetUrl(targetUrl)
- }
- // ,
- // function (index) {
- // http.ajax.handleTargetUrl(targetUrl)
- // layer.close(index);
- // }
- );
- }
- },
- handleTargetUrl: function (targetUrl) {
- if (!targetUrl) {
- parent.location.href = http.appPath;
- } else {
- parent.location.href = targetUrl;
- }
- },
- handleErrorResponse: function (jqXHR, userOptions, $dfd) {
- if (userOptions.customHandleError !== false) {
- switch (jqXHR.status) {
- case 401:
- http.ajax.showErrorAndRedirectUrl(http.ajax.defaultError401, http.appPath);
- break;
- case 403:
- http.ajax.showError(http.ajax.defaultError403);
- break;
- case 404:
- http.ajax.showError(http.ajax.defaultError404);
- break;
- default:
- http.ajax.showError(http.ajax.defaultError);
- break;
- }
- }
- $dfd.reject.apply(this, arguments);
- userOptions.error && userOptions.error.apply(this, arguments);
- },
- ajaxSendHandler: function (event, request, settings) {
- var token = http.ajax.getToken();
- if (!token) {
- return;
- }
- if (!settings.headers || settings.headers[http.ajax.tokenHeaderName] === undefined) {
- request.setRequestHeader(http.ajax.tokenHeaderName, token);
- }
- },
- setToken: function (token) {
- localStorage.setItem(http.ajax.tokenCookieName, token);
- },
- delToken: function () {
- localStorage.removeItem(http.ajax.tokenCookieName);
- },
- getToken: function () {
- return localStorage.getItem(http.ajax.tokenCookieName);
- },
- tokenCookieName :'XSRF-TOKEN',
- tokenHeaderName : 'AUTH-TOKEN',
- getCookieValue: function (key) {
- var equalities = document.cookie.split('; ');
- for (var i = 0; i < equalities.length; i++) {
- if (!equalities[i]) {
- continue;
- }
- var splitted = equalities[i].split('=');
- if (splitted.length != 2) {
- continue;
- }
- if (decodeURIComponent(splitted[0]) === key) {
- return decodeURIComponent(splitted[1] || '');
- }
- }
- return null;
- }
- });
- $(document).ajaxSend(function (event, request, settings) {
- return http.ajax.ajaxSendHandler(event, request, settings);
- });
- exports('mhttp', http);
- });
|