华西海圻ELN前端工程
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

326 lines
11 KiB

  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 i18n from '@/lang'
  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: 90000
  20. })
  21. // request拦截器
  22. service.interceptors.request.use(
  23. (config) => {
  24. // 是否需要设置 token
  25. const isToken = (config.headers || {}).isToken === false
  26. // 是否需要防止数据重复提交
  27. const isRepeatSubmit = (config.headers || {}).repeatSubmit === false
  28. if (getToken() && !isToken) {
  29. config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  30. }
  31. // get请求映射params参数
  32. if (config.method === 'get' && config.params) {
  33. let url = config.url + '?' + tansParams(config.params)
  34. url = url.slice(0, -1)
  35. config.params = {}
  36. config.url = url
  37. }
  38. if (
  39. !isRepeatSubmit &&
  40. (config.method === 'post' || config.method === 'put')
  41. ) {
  42. const requestObj = {
  43. url: config.url,
  44. data:
  45. typeof config.data === 'object'
  46. ? JSON.stringify(config.data)
  47. : config.data,
  48. time: new Date().getTime()
  49. }
  50. const requestSize = Object.keys(JSON.stringify(requestObj)).length // 请求数据大小
  51. const limitSize = 5 * 1024 * 1024 // 限制存放数据5M
  52. if (requestSize >= limitSize) {
  53. console.warn(
  54. `[${config.url}]: ` +
  55. '请求数据大小超出允许的5M限制,无法进行防重复提交验证。'
  56. )
  57. return config
  58. }
  59. // const sessionObj = cache.session.getJSON('sessionObj')
  60. // if (
  61. // sessionObj === undefined ||
  62. // sessionObj === null ||
  63. // sessionObj === ''
  64. // ) {
  65. // cache.session.setJSON('sessionObj', requestObj)
  66. // } else {
  67. // const s_url = sessionObj.url // 请求地址
  68. // const s_data = sessionObj.data // 请求数据
  69. // const s_time = sessionObj.time // 请求时间
  70. // const interval = 1000 // 间隔时间(ms),小于此时间视为重复提交
  71. // if (
  72. // s_data === requestObj.data &&
  73. // requestObj.time - s_time < interval &&
  74. // s_url === requestObj.url
  75. // ) {
  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. },
  86. (error) => {
  87. console.log(error)
  88. Promise.reject(error)
  89. }
  90. )
  91. // 响应拦截器
  92. service.interceptors.response.use(
  93. (res) => {
  94. // 未设置状态码则默认成功状态
  95. const code = res.data.code || 200
  96. // 获取错误信息
  97. const msg = errorCode[code] || res.data.msg || errorCode['default']
  98. // 二进制数据则直接返回
  99. if (
  100. res.request.responseType === 'blob' ||
  101. res.request.responseType === 'arraybuffer'
  102. ) {
  103. return res.data
  104. }
  105. if (code === 401) {
  106. store.dispatch('LogOut').then(() => {
  107. // location.href = '/user/work'
  108. })
  109. if (!isRelogin.show) {
  110. isRelogin.show = true
  111. // MessageBox.confirm(
  112. // '登录状态已过期,您可以继续留在该页面,或者重新登录',
  113. // '系统提示',
  114. // {
  115. // confirmButtonText: '重新登录',
  116. // cancelButtonText: '取消',
  117. // type: 'warning'
  118. // }
  119. // )
  120. // .then(() => {
  121. // isRelogin.show = false
  122. // store.dispatch('LogOut').then(() => {
  123. // location.href = '/user/work'
  124. // })
  125. // })
  126. // .catch(() => {
  127. // isRelogin.show = false
  128. // })
  129. MessageBox.prompt(
  130. i18n.t('system.timeOutContent'),
  131. i18n.t('system.tip'),
  132. {
  133. confirmButtonText: i18n.t('system.timeOutEnter'),
  134. cancelButtonText: i18n.t('form.cancel'),
  135. inputPattern: /^\S+$/,
  136. inputType: 'password',
  137. inputPlaceholder: i18n.t('login.password'),
  138. inputErrorMessage: i18n.t('login.password'),
  139. showClose: false,
  140. closeOnPressEscape: false,
  141. closeOnClickModal: false,
  142. beforeClose: (action, instance, done) => {
  143. if (action === 'confirm') {
  144. let password = instance.inputValue
  145. store
  146. .dispatch('Login', {
  147. username: store.getters.name,
  148. password: password,
  149. force: false
  150. })
  151. .then(() => {
  152. console.log('重新登录成功')
  153. isRelogin.show = false
  154. done()
  155. })
  156. .catch((err) => {
  157. if (err && err.message === 'exists') {
  158. isRelogin.show = false
  159. done()
  160. setTimeout(() => {
  161. MessageBox.confirm(
  162. i18n.t('system.crowdOut'),
  163. i18n.t('system.tip'),
  164. {
  165. confirmButtonText: i18n.t('form.confirm'),
  166. cancelButtonText: i18n.t('form.cancel'),
  167. type: 'warning',
  168. showClose: false,
  169. closeOnPressEscape: false,
  170. closeOnClickModal: false
  171. }
  172. )
  173. .then(() => {
  174. store
  175. .dispatch('Login', {
  176. username: store.getters.name,
  177. password: password,
  178. force: true
  179. })
  180. .then(() => {
  181. console.log('重新登录成功')
  182. })
  183. .catch((err) => {
  184. console.log(
  185. '重新登录失败' + JSON.stringify(err)
  186. )
  187. return false
  188. })
  189. })
  190. .catch(() => {
  191. // if (this.captchaEnabled) {
  192. // this.getCode()
  193. // }
  194. location.href = '/user/work'
  195. })
  196. }, 0)
  197. } else {
  198. // if (this.captchaEnabled) {
  199. // this.getCode()
  200. // }
  201. return false
  202. }
  203. })
  204. } else {
  205. done()
  206. isRelogin.show = false
  207. location.href = '/user/work'
  208. }
  209. }
  210. }
  211. )
  212. .then(({ value }) => {
  213. isRelogin.show = false
  214. })
  215. .catch(() => {
  216. isRelogin.show = false
  217. location.href = '/user/work'
  218. })
  219. }
  220. return Promise.reject(i18n.t('system.timeOutTip'))
  221. } else if (code === 500) {
  222. if (msg !== 'exists') {
  223. Message({ message: msg, type: 'error' })
  224. }
  225. return Promise.reject(new Error(msg))
  226. } else if (code === 601) {
  227. Message({ message: msg, type: 'warning' })
  228. return Promise.reject('error')
  229. } else if (code !== 200) {
  230. Notification.error({ title: msg })
  231. return Promise.reject('error')
  232. } else {
  233. return res.data
  234. }
  235. },
  236. (error) => {
  237. console.log('err' + error)
  238. let { message } = error
  239. if (message == 'Network Error') {
  240. message = '后端接口连接异常'
  241. } else if (message.includes('timeout')) {
  242. message = '系统接口请求超时'
  243. } else if (message.includes('Request failed with status code')) {
  244. message = '系统接口' + message.substr(message.length - 3) + '异常'
  245. }
  246. Message({ message: message, type: 'error', duration: 5 * 1000 })
  247. return Promise.reject(error)
  248. }
  249. )
  250. export function login(username, password, force) {
  251. store
  252. .dispatch('Login', { username: username, password: password, force: force })
  253. .then(() => {
  254. console.log('重新登录成功')
  255. })
  256. .catch((err) => {
  257. if (err && err.message === 'exists') {
  258. MessageBox.confirm(i18n.t('system.crowdOut'), i18n.t('system.tip'), {
  259. confirmButtonText: i18n.t('form.confirm'),
  260. cancelButtonText: i18n.t('form.cancel'),
  261. type: 'warning'
  262. })
  263. .then(() => {
  264. login(username, password, true)
  265. })
  266. .catch(() => {
  267. // if (this.captchaEnabled) {
  268. // this.getCode()
  269. // }
  270. })
  271. } else {
  272. // if (this.captchaEnabled) {
  273. // this.getCode()
  274. // }
  275. }
  276. })
  277. }
  278. // 通用下载方法
  279. export function download(url, params, filename, config) {
  280. downloadLoadingInstance = Loading.service({
  281. text: '正在下载数据,请稍候',
  282. spinner: 'el-icon-loading',
  283. background: 'rgba(0, 0, 0, 0.7)'
  284. })
  285. return service
  286. .post(url, params, {
  287. transformRequest: [
  288. (params) => {
  289. return tansParams(params)
  290. }
  291. ],
  292. headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  293. responseType: 'blob',
  294. ...config
  295. })
  296. .then(async (data) => {
  297. const isBlob = blobValidate(data)
  298. if (isBlob) {
  299. const blob = new Blob([data])
  300. saveAs(blob, filename)
  301. } else {
  302. const resText = await data.text()
  303. const rspObj = JSON.parse(resText)
  304. const errMsg =
  305. errorCode[rspObj.code] || rspObj.msg || errorCode['default']
  306. Message.error(errMsg)
  307. }
  308. downloadLoadingInstance.close()
  309. })
  310. .catch((r) => {
  311. console.error(r)
  312. Message.error('下载文件出现错误,请联系管理员!')
  313. downloadLoadingInstance.close()
  314. })
  315. }
  316. export default service