request.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  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. let downloadLoadingInstance;
  11. // 是否显示重新登录
  12. export let isRelogin = { show: false };
  13. axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
  14. // 创建axios实例
  15. const service = axios.create({
  16. // axios中请求配置有baseURL选项,表示请求URL公共部分
  17. baseURL: process.env.VUE_APP_BASE_API,
  18. // 超时
  19. timeout: 60 * 60 * 1000
  20. })
  21. // request拦截器
  22. service.interceptors.request.use(config => {
  23. // 是否需要设置 token
  24. const isToken = (config.headers || {}).isToken === false
  25. // 是否需要防止数据重复提交
  26. const isRepeatSubmit = (config.headers || {}).repeatSubmit === false
  27. if (getToken() && !isToken) {
  28. config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  29. }
  30. // 请求参数加密
  31. if (process.env.VUE_APP_AES_ENCRYPT_ENABLED == 'true') {
  32. if (config.data) {
  33. console.log(JSON.stringify(config.data));
  34. config.data = {
  35. // 加密参数
  36. dataParams: encodeURIComponent(aes.encrypt(JSON.stringify(config.data)))
  37. }
  38. } else if (config.params) {
  39. console.log(JSON.stringify(config.params));
  40. config.params = {
  41. // 加密参数
  42. dataParams: encodeURIComponent(aes.encrypt(JSON.stringify(config.params)))
  43. }
  44. } else {
  45. let noData = {
  46. noData: new Date().getTime()
  47. }
  48. config.params = {
  49. // 加密参数
  50. dataParams: encodeURIComponent(aes.encrypt(JSON.stringify(noData)))
  51. }
  52. }
  53. }
  54. // get请求映射params参数
  55. if (config.method === 'get' && config.params) {
  56. let url = config.url + '?' + tansParams(config.params);
  57. url = url.slice(0, -1);
  58. config.params = {};
  59. config.url = url;
  60. }
  61. if (!isRepeatSubmit && (config.method === 'post' || config.method === 'put')) {
  62. const requestObj = {
  63. url: config.url,
  64. data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data,
  65. time: new Date().getTime()
  66. }
  67. const sessionObj = cache.session.getJSON('sessionObj')
  68. if (sessionObj === undefined || sessionObj === null || sessionObj === '') {
  69. cache.session.setJSON('sessionObj', requestObj)
  70. } else {
  71. const s_url = sessionObj.url; // 请求地址
  72. const s_data = sessionObj.data; // 请求数据
  73. const s_time = sessionObj.time; // 请求时间
  74. const interval = 1000; // 间隔时间(ms),小于此时间视为重复提交
  75. if (s_data === requestObj.data && requestObj.time - s_time < interval && s_url === requestObj.url) {
  76. const message = '数据正在处理,请勿重复提交';
  77. console.warn(`[${s_url}]: ` + message)
  78. return Promise.reject(new Error(message))
  79. } else {
  80. cache.session.setJSON('sessionObj', requestObj)
  81. }
  82. }
  83. }
  84. return config
  85. }, error => {
  86. console.log(error)
  87. Promise.reject(error)
  88. })
  89. // 响应拦截器
  90. service.interceptors.response.use(res => {
  91. // 未设置状态码则默认成功状态
  92. const code = res.data.code || 200;
  93. // 获取错误信息
  94. const msg = errorCode[code] || res.data.msg || errorCode['default']
  95. // 二进制数据则直接返回
  96. if(res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer'){
  97. return res.data
  98. }
  99. if (code === 401) {
  100. if (!isRelogin.show) {
  101. isRelogin.show = true;
  102. MessageBox.confirm('登录状态已过期,您可以继续留在该页面,或者重新登录', '系统提示', {
  103. confirmButtonText: '重新登录',
  104. cancelButtonText: '取消',
  105. type: 'warning'
  106. }
  107. ).then(() => {
  108. isRelogin.show = false;
  109. store.dispatch('LogOut').then(() => {
  110. location.href = '/ruoyi-vue-web/index';
  111. })
  112. }).catch(() => {
  113. isRelogin.show = false;
  114. });
  115. }
  116. return Promise.reject('无效的会话,或者会话已过期,请重新登录。')
  117. } else if (code === 500) {
  118. Message({
  119. message: msg,
  120. type: 'error'
  121. })
  122. return Promise.reject(new Error(msg))
  123. } else if (code !== 200) {
  124. Notification.error({
  125. title: msg
  126. })
  127. return Promise.reject('error')
  128. } else {
  129. return res.data
  130. }
  131. },
  132. error => {
  133. console.log('err' + error)
  134. let { message } = error;
  135. if (message == "Network Error") {
  136. message = "后端接口连接异常";
  137. }
  138. else if (message.includes("timeout")) {
  139. message = "系统接口请求超时";
  140. }
  141. else if (message.includes("Request failed with status code")) {
  142. message = "系统接口" + message.substr(message.length - 3) + "异常";
  143. }
  144. Message({
  145. message: message,
  146. type: 'error',
  147. duration: 5 * 1000
  148. })
  149. return Promise.reject(error)
  150. }
  151. )
  152. // 通用下载方法
  153. export function download(url, params, filename) {
  154. downloadLoadingInstance = Loading.service({ text: "正在下载数据,请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
  155. return service.post(url, params, {
  156. transformRequest: [(params) => { return tansParams(params) }],
  157. headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  158. responseType: 'blob'
  159. }).then(async (data) => {
  160. const isLogin = await blobValidate(data);
  161. if (isLogin) {
  162. const blob = new Blob([data])
  163. saveAs(blob, filename)
  164. } else {
  165. const resText = await data.text();
  166. const rspObj = JSON.parse(resText);
  167. const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
  168. Message.error(errMsg);
  169. }
  170. downloadLoadingInstance.close();
  171. }).catch((r) => {
  172. console.error(r)
  173. Message.error('下载文件出现错误,请联系管理员!')
  174. downloadLoadingInstance.close();
  175. })
  176. }
  177. export default service