request.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. import axios from 'axios'
  2. import { Notification, MessageBox, Message, Loading } from 'element-ui'
  3. import store from '@/store'
  4. import { getToken } from '@/utils/auth'
  5. import errorCode from '@/utils/errorCode'
  6. import { tansParams, blobValidate } from "@/utils/ruoyi";
  7. import cache from '@/plugins/cache'
  8. import { saveAs } from 'file-saver'
  9. import aes from './aes.js'
  10. import Vue from 'vue';
  11. let downloadLoadingInstance;
  12. // 是否显示重新登录
  13. export let isRelogin = { show: false };
  14. axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
  15. // 创建axios实例
  16. const service = axios.create({
  17. // axios中请求配置有baseURL选项,表示请求URL公共部分
  18. baseURL: process.env.VUE_APP_BASE_API,
  19. // 超时
  20. timeout: 60 * 60 * 1000
  21. })
  22. // 正在进行中的请求列表
  23. let reqList = [];
  24. let count = 0; // 请求接口计数器
  25. /**
  26. * 阻止重复请求
  27. * @param {array} reqList - 请求缓存列表
  28. * @param {string} url - 当前请求地址
  29. * @param {function} cancel - 请求中断函数
  30. * @param {string} errorMessage - 请求中断时需要显示的错误信息
  31. */
  32. const stopRepeatRequest = function (reqList, url, cancel, errorMessage) {
  33. const errorMsg = errorMessage || ''
  34. for (let i = 0; i < reqList.length; i++) {
  35. if (reqList[i].url === url) {
  36. // reqList[i].cancel(errorMsg); // 中断上一个重复请求
  37. reqList[i].cancel(); // 中断上一个重复请求
  38. reqList.splice(i, 1); // 删除上一个重复请求
  39. reqList.push({ // 存储新的请求
  40. url,
  41. cancel
  42. })
  43. return
  44. }
  45. }
  46. reqList.push({
  47. url,
  48. cancel
  49. })
  50. }
  51. /**
  52. * 允许某个请求可以继续进行
  53. * @param {array} reqList 全部请求列表
  54. * @param {string} url 请求地址
  55. */
  56. const allowRequest = function (reqList, url) {
  57. for (let i = 0; i < reqList.length; i++) {
  58. if (reqList[i] === url) {
  59. reqList.splice(i, 1)
  60. break
  61. }
  62. }
  63. }
  64. // request拦截器
  65. service.interceptors.request.use(config => {
  66. Vue.prototype.$layer.loading({ content: '请稍等!' });
  67. let cancel = null;
  68. // 设置cancelToken对象
  69. config.cancelToken = new axios.CancelToken(function (c) {
  70. cancel = c
  71. })
  72. // 阻止重复请求。当上个请求未完成时,相同的请求不会进行
  73. stopRepeatRequest(reqList, config.url, cancel, `${config.url} 请求被中断`)
  74. // ++count;
  75. // 是否需要设置 token
  76. const isToken = (config.headers || {}).isToken === false
  77. // 是否需要防止数据重复提交
  78. const isRepeatSubmit = (config.headers || {}).repeatSubmit === false
  79. if (getToken() && !isToken) {
  80. config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  81. }
  82. // 请求参数加密
  83. if (process.env.VUE_APP_AES_ENCRYPT_ENABLED == 'true') {
  84. if (config.data) {
  85. config.data = {
  86. // 加密参数
  87. dataParams: encodeURIComponent(aes.encrypt(JSON.stringify(config.data)))
  88. }
  89. } else if (config.params) {
  90. config.params = {
  91. // 加密参数
  92. dataParams: encodeURIComponent(aes.encrypt(JSON.stringify(config.params)))
  93. }
  94. } else {
  95. let noData = {
  96. noData: new Date().getTime()
  97. }
  98. config.params = {
  99. // 加密参数
  100. dataParams: encodeURIComponent(aes.encrypt(JSON.stringify(noData)))
  101. }
  102. }
  103. }
  104. // get请求映射params参数
  105. if (config.method === 'get' && config.params) {
  106. let url = config.url + '?' + tansParams(config.params);
  107. url = url.slice(0, -1);
  108. config.params = {};
  109. config.url = url;
  110. }
  111. if (!isRepeatSubmit && (config.method === 'post' || config.method === 'put')) {
  112. const requestObj = {
  113. url: config.url,
  114. data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data,
  115. time: new Date().getTime()
  116. }
  117. const sessionObj = cache.session.getJSON('sessionObj')
  118. if (sessionObj === undefined || sessionObj === null || sessionObj === '') {
  119. cache.session.setJSON('sessionObj', requestObj)
  120. } else {
  121. cache.session.setJSON('sessionObj', requestObj)
  122. }
  123. }
  124. return config
  125. }, error => {
  126. Promise.reject(error)
  127. })
  128. // 响应拦截器
  129. service.interceptors.response.use(res => {
  130. // setTimeout(() => {
  131. // Vue.prototype.$layer.closeAll('loading');
  132. // }, 500);
  133. if(res.status == 200) Vue.prototype.$layer.closeAll('loading');
  134. // --count;
  135. // if (count === 0) {
  136. // Vue.prototype.$layer.closeAll('loading');
  137. // }
  138. // 未设置状态码则默认成功状态
  139. const code = res.data.code || 200;
  140. // 获取错误信息
  141. const msg = errorCode[code] || res.data.msg || errorCode['default']
  142. // 二进制数据则直接返回
  143. if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
  144. return res.data
  145. }
  146. if (code === 401) {
  147. if (!isRelogin.show) {
  148. isRelogin.show = true;
  149. MessageBox.confirm('登录状态已过期,您可以继续留在该页面,或者重新登录', '系统提示', {
  150. confirmButtonText: '重新登录',
  151. cancelButtonText: '取消',
  152. type: 'warning'
  153. }
  154. ).then(() => {
  155. isRelogin.show = false;
  156. store.dispatch('LogOut').then(() => {
  157. location.href = '/admin/index';
  158. })
  159. }).catch(() => {
  160. isRelogin.show = false;
  161. });
  162. }
  163. return Promise.reject('无效的会话,或者会话已过期,请重新登录。')
  164. } else if (code === 500) {
  165. Message({
  166. message: msg,
  167. type: 'error'
  168. })
  169. return Promise.reject(new Error(msg))
  170. } else if (code !== 200) {
  171. Notification.error({
  172. title: msg
  173. })
  174. return Promise.reject('error')
  175. } else {
  176. return res.data
  177. }
  178. },
  179. error => {
  180. setTimeout(() => {
  181. Vue.prototype.$layer.closeAll('loading');
  182. }, 500);
  183. let { message } = error;
  184. if (message == "Network Error") {
  185. message = "后端接口连接异常";
  186. }
  187. else if (message.includes("timeout")) {
  188. message = "系统接口请求超时";
  189. }
  190. else if (message.includes("Request failed with status code")) {
  191. message = "系统接口" + message.substr(message.length - 3) + "异常";
  192. }
  193. Message({
  194. message: message,
  195. type: 'error',
  196. duration: 5 * 1000
  197. })
  198. return Promise.reject(error)
  199. }
  200. )
  201. // 通用下载方法
  202. export function download(url, params, filename) {
  203. downloadLoadingInstance = Loading.service({ text: "正在下载数据,请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
  204. return service.post(url, params, {
  205. transformRequest: [(params) => { return tansParams(params) }],
  206. headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  207. responseType: 'blob'
  208. }).then(async (data) => {
  209. const isLogin = await blobValidate(data);
  210. if (isLogin) {
  211. const blob = new Blob([data])
  212. saveAs(blob, filename)
  213. } else {
  214. const resText = await data.text();
  215. const rspObj = JSON.parse(resText);
  216. const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
  217. Message.error(errMsg);
  218. }
  219. downloadLoadingInstance.close();
  220. }).catch((r) => {
  221. console.error(r)
  222. Message.error('下载文件出现错误,请联系管理员!')
  223. downloadLoadingInstance.close();
  224. })
  225. }
  226. export default service