request.js 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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. let cancel = null;
  67. // 设置cancelToken对象
  68. config.cancelToken = new axios.CancelToken(function (c) {
  69. cancel = c
  70. })
  71. // 阻止重复请求。当上个请求未完成时,相同的请求不会进行
  72. stopRepeatRequest(reqList, config.url, cancel, `${config.url} 请求被中断`)
  73. // ++count;
  74. Vue.prototype.$layer.loading({ content: '请稍等!' });
  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. console.log(JSON.stringify(config.data));
  86. config.data = {
  87. // 加密参数
  88. dataParams: encodeURIComponent(aes.encrypt(JSON.stringify(config.data)))
  89. }
  90. } else if (config.params) {
  91. console.log(JSON.stringify(config.params));
  92. config.params = {
  93. // 加密参数
  94. dataParams: encodeURIComponent(aes.encrypt(JSON.stringify(config.params)))
  95. }
  96. } else {
  97. let noData = {
  98. noData: new Date().getTime()
  99. }
  100. config.params = {
  101. // 加密参数
  102. dataParams: encodeURIComponent(aes.encrypt(JSON.stringify(noData)))
  103. }
  104. }
  105. }
  106. // get请求映射params参数
  107. if (config.method === 'get' && config.params) {
  108. let url = config.url + '?' + tansParams(config.params);
  109. url = url.slice(0, -1);
  110. config.params = {};
  111. config.url = url;
  112. }
  113. if (!isRepeatSubmit && (config.method === 'post' || config.method === 'put')) {
  114. const requestObj = {
  115. url: config.url,
  116. data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data,
  117. time: new Date().getTime()
  118. }
  119. const sessionObj = cache.session.getJSON('sessionObj')
  120. if (sessionObj === undefined || sessionObj === null || sessionObj === '') {
  121. cache.session.setJSON('sessionObj', requestObj)
  122. } else {
  123. cache.session.setJSON('sessionObj', requestObj)
  124. }
  125. }
  126. return config
  127. }, error => {
  128. console.log(error)
  129. Promise.reject(error)
  130. })
  131. // 响应拦截器
  132. service.interceptors.response.use(res => {
  133. // setTimeout(() => {
  134. // Vue.prototype.$layer.closeAll('loading');
  135. // }, 500);
  136. if(res.status == 200) Vue.prototype.$layer.closeAll('loading');
  137. // --count;
  138. // if (count === 0) {
  139. // Vue.prototype.$layer.closeAll('loading');
  140. // }
  141. // 未设置状态码则默认成功状态
  142. const code = res.data.code || 200;
  143. // 获取错误信息
  144. const msg = errorCode[code] || res.data.msg || errorCode['default']
  145. // 二进制数据则直接返回
  146. if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
  147. return res.data
  148. }
  149. if (code === 401) {
  150. if (!isRelogin.show) {
  151. isRelogin.show = true;
  152. MessageBox.confirm('登录状态已过期,您可以继续留在该页面,或者重新登录', '系统提示', {
  153. confirmButtonText: '重新登录',
  154. cancelButtonText: '取消',
  155. type: 'warning'
  156. }
  157. ).then(() => {
  158. isRelogin.show = false;
  159. store.dispatch('LogOut').then(() => {
  160. location.href = '/index';
  161. })
  162. }).catch(() => {
  163. isRelogin.show = false;
  164. });
  165. }
  166. return Promise.reject('无效的会话,或者会话已过期,请重新登录。')
  167. } else if (code === 500) {
  168. Message({
  169. message: msg,
  170. type: 'error'
  171. })
  172. return Promise.reject(new Error(msg))
  173. } else if (code !== 200) {
  174. Notification.error({
  175. title: msg
  176. })
  177. return Promise.reject('error')
  178. } else {
  179. return res.data
  180. }
  181. },
  182. error => {
  183. console.log('err' + error)
  184. setTimeout(() => {
  185. Vue.prototype.$layer.closeAll('loading');
  186. }, 500);
  187. let { message } = error;
  188. if (message == "Network Error") {
  189. message = "后端接口连接异常";
  190. }
  191. else if (message.includes("timeout")) {
  192. message = "系统接口请求超时";
  193. }
  194. else if (message.includes("Request failed with status code")) {
  195. message = "系统接口" + message.substr(message.length - 3) + "异常";
  196. }
  197. Message({
  198. message: message,
  199. type: 'error',
  200. duration: 5 * 1000
  201. })
  202. return Promise.reject(error)
  203. }
  204. )
  205. // 通用下载方法
  206. export function download(url, params, filename) {
  207. downloadLoadingInstance = Loading.service({ text: "正在下载数据,请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
  208. return service.post(url, params, {
  209. transformRequest: [(params) => { return tansParams(params) }],
  210. headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  211. responseType: 'blob'
  212. }).then(async (data) => {
  213. const isLogin = await blobValidate(data);
  214. if (isLogin) {
  215. const blob = new Blob([data])
  216. saveAs(blob, filename)
  217. } else {
  218. const resText = await data.text();
  219. const rspObj = JSON.parse(resText);
  220. const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
  221. Message.error(errMsg);
  222. }
  223. downloadLoadingInstance.close();
  224. }).catch((r) => {
  225. console.error(r)
  226. Message.error('下载文件出现错误,请联系管理员!')
  227. downloadLoadingInstance.close();
  228. })
  229. }
  230. export default service