request.js 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. import axios from 'axios'
  2. import { MessageBox, Message } from '@zjlib/element-ui2'
  3. import store from '@/store'
  4. import { getToken } from '@/utils/auth'
  5. // create an axios instance
  6. const service = axios.create({
  7. baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  8. // withCredentials: true, // send cookies when cross-domain requests
  9. timeout: 300000 // request timeout
  10. })
  11. const whiteCodes = [200, 201, 4444]
  12. // request interceptor
  13. service.interceptors.request.use(
  14. config => {
  15. // do something before request is sent
  16. if (store.getters.token) {
  17. // let each request carry token
  18. // ['X-Token'] is a custom headers key
  19. // please modify it according to the actual situation
  20. config.headers['x-token'] = store.getters.token
  21. }
  22. return config
  23. },
  24. error => {
  25. // do something with request error
  26. console.log(error) // for debug
  27. return Promise.reject(error)
  28. }
  29. )
  30. // response interceptor
  31. service.interceptors.response.use(
  32. /**
  33. * If you want to get http information such as headers or status
  34. * Please return response => response
  35. */
  36. /**
  37. * Determine the request status by custom code
  38. * Here is just an example
  39. * You can also judge the status by HTTP Status Code
  40. */ response => {
  41. const res = response.data
  42. // if the custom code is not 20000, it is judged as an error.
  43. if (whiteCodes.indexOf(res.code) < 0) {
  44. if (JSON.parse(response.config.data || '{}')?.returnErr || response.config.params?.returnErr) {
  45. return Promise.reject(res)
  46. }
  47. Message({
  48. message: res.message || 'Error',
  49. type: 'error',
  50. duration: 5 * 1000
  51. })
  52. // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
  53. if (res.code === 1001) {
  54. // to re-login
  55. MessageBox.confirm('登录失效,您可以取消停留在此页面,或重新登录', '登录失效', {
  56. confirmButtonText: '重新登录',
  57. cancelButtonText: '取消',
  58. type: 'warning'
  59. }).then(() => {
  60. store.dispatch('user/resetToken').then(() => {
  61. location.reload()
  62. })
  63. })
  64. } else if (res.code === 4004) {
  65. // to re-login
  66. MessageBox.confirm('账号过期,请前往续费', '账号过期', {
  67. confirmButtonText: '去续费',
  68. cancelButtonText: '取消',
  69. type: 'warning'
  70. }).then(() => {
  71. window.location.href = window.location.href.split("#")[0] + "#/setting/personal?isRenew=true"
  72. })
  73. }
  74. return Promise.reject(new Error(res.message || 'Error'))
  75. } else {
  76. return res
  77. }
  78. },
  79. error => {
  80. console.log('err' + error) // for debug
  81. Message({
  82. message: error.message,
  83. type: 'error',
  84. duration: 5 * 1000
  85. })
  86. return Promise.reject(error)
  87. }
  88. )
  89. export default service
  90. function zhapi(add, path) {
  91. if (add[add.length - 1] == '/' && path[0] == '/') {
  92. return add + path.substr(1)
  93. }
  94. return add + path
  95. }
  96. // post方式导出文件
  97. export function postBlob(data) {
  98. return new Promise(function (r, j) {
  99. axios({
  100. method: 'post',
  101. url: zhapi(process.env.VUE_APP_BASE_API, data.url), // 后端接口地址
  102. responseType: 'blob', // bolb格式的请求方式
  103. headers: {
  104. 'x-token': getToken() // 请求头
  105. },
  106. data: data.data // 需要传给后端的请求参数体
  107. })
  108. .then(res => {
  109. const BLOB = res.data
  110. const fileReader = new FileReader()
  111. fileReader.readAsDataURL(BLOB) // 对请求返回的文件进行处理
  112. fileReader.onload = e => {
  113. const a = document.createElement('a')
  114. a.download = data.name
  115. a.href = e.target.result
  116. document.body.appendChild(a)
  117. a.click()
  118. document.body.removeChild(a)
  119. }
  120. r()
  121. })
  122. .catch(err => {
  123. console.log(err.message)
  124. j()
  125. })
  126. })
  127. }
  128. // get方式导出文件
  129. export function getBlob(data) {
  130. return new Promise(function (r, j) {
  131. axios({
  132. url: zhapi(process.env.VUE_APP_BASE_API, data.url),
  133. method: 'get',
  134. responseType: 'blob',
  135. params: data.params, // 与post传参方式不同之处
  136. headers: {
  137. 'x-token': getToken() // 请求头
  138. }
  139. })
  140. .then(res => {
  141. var blob = new Blob([res.data], {
  142. type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8'
  143. })
  144. var filename = data.name + '.xlsx'
  145. var downloadElement = document.createElement('a')
  146. var href = window.URL.createObjectURL(blob) // 创建下载的链接
  147. downloadElement.style.display = 'none'
  148. downloadElement.href = href
  149. downloadElement.download = filename // 下载后文件名
  150. document.body.appendChild(downloadElement)
  151. downloadElement.click() // 点击下载
  152. document.body.removeChild(downloadElement) // 下载完成移除元素
  153. window.URL.revokeObjectURL(href) // 释放掉blob对象
  154. r()
  155. })
  156. .catch(err => {
  157. console.log(err.message)
  158. j()
  159. })
  160. })
  161. }
  162. /**
  163. * 导入功能
  164. * @param {*} url
  165. * @param {*} formData
  166. * @param {*} id
  167. */
  168. export function handleImport(url, formData, id = '') {
  169. return new Promise((resolve, reject) => {
  170. axios
  171. .post(zhapi(process.env.VUE_APP_BASE_API, url), formData, {
  172. headers: {
  173. 'Content-Type': 'multipart/form-data',
  174. 'x-token': getToken(),
  175. id
  176. }
  177. })
  178. .then(res => {
  179. if (res.data.code !== 200) {
  180. reject(new Error(res.data.message || 'Error'))
  181. return
  182. }
  183. resolve(res.data)
  184. })
  185. .catch(err => {
  186. reject(err)
  187. })
  188. })
  189. }