华西海圻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.

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