httputils.js 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. import axios from 'axios'
  2. import store from '@/store'
  3. import router from '@/router'
  4. // import { MessageBox } from 'element-ui'
  5. import { Toast } from 'vant'
  6. var CancelToken = axios.CancelToken
  7. var cancel
  8. // 创建axios实例
  9. const axiosservice = axios.create({
  10. timeout: 60 * 1000, // 请求超时时间
  11. retry: 4, //重新请求次数
  12. retryDelay: 1000, //重新请求的间隔
  13. credentials: true, // 接口每次请求会跨域携带cookie
  14. cancelToken: new CancelToken(function executor(c) {
  15. // executor 函数接收一个 cancel 函数作为参数
  16. cancel = c
  17. }),
  18. })
  19. axiosservice.interceptors.request.use(
  20. (config) => {
  21. config.withCredentials = true // 允许携带token ,这个是解决跨域产生的相关问题
  22. let isPreview = null
  23. let token = store.getters['ssoToken']
  24. if (config.url.indexOf('/data') > -1) {
  25. config.headers = {
  26. 'sso-token': token,
  27. // isPreview, //默认false,当预览开启的时候是true
  28. }
  29. }
  30. return config
  31. },
  32. (error) => {
  33. return Promise.reject(error)
  34. }
  35. )
  36. axiosservice.interceptors.response.use(
  37. function(res) {
  38. //在这里对返回的数据进行处理
  39. let resp = res.data
  40. // if (resp.result === 'unauthc') {
  41. // store.commit('logined', false)
  42. // MessageBox.confirm('未登陆或登陆信息已失效, 是否重新登陆?', '提示', {
  43. // confirmButtonText: '确定',
  44. // cancelButtonText: '取消',
  45. // type: 'error',
  46. // })
  47. // .then((resp) => {
  48. // window.location.reload()
  49. // })
  50. // .catch((error) => {
  51. // console.log('asdfasdfsad')
  52. // })
  53. // } else if (resp.error == 'Unauthorized') {
  54. // MessageBox.alert('无权操作', {
  55. // title: '警告',
  56. // type: 'error',
  57. // })
  58. // }
  59. return res
  60. },
  61. function(err) {
  62. // TODO: 接口错误处理
  63. let { data } = err.response
  64. let message = data.path + data.error
  65. // console.log(message)
  66. Toast.setDefaultOptions({ duration: 3000 })
  67. Toast('网络异常,请稍后再试')
  68. if (err.response.status == 401) {
  69. // store.commit('SETISREQUESTtAUTH', 'err')
  70. // router.push({
  71. // path: '404',
  72. // })
  73. }
  74. return Promise.reject(err)
  75. }
  76. )
  77. /* 下载方法 */
  78. function downFile(blob, fileName) {
  79. // 非IE下载
  80. if ('download' in document.createElement('a')) {
  81. let link = document.createElement('a')
  82. link.href = window.URL.createObjectURL(blob) // 创建下载的链接
  83. link.download = fileName // 下载后文件名
  84. link.style.display = 'none'
  85. document.body.appendChild(link)
  86. link.click() // 点击下载
  87. window.URL.revokeObjectURL(link.href) // 释放掉blob对象
  88. document.body.removeChild(link) // 下载完成移除元素
  89. } else {
  90. // IE10+下载
  91. window.navigator.msSaveBlob(blob, fileName)
  92. }
  93. }
  94. export default {
  95. //获取cookie
  96. getCookie(name) {
  97. var arr,
  98. reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)')
  99. if ((arr = document.cookie.match(reg))) {
  100. return unescape(arr[2])
  101. } else {
  102. /* 如果没有参数,那么就获取本域下的所有cookie */
  103. return document.cookie
  104. }
  105. },
  106. async getJson(url, params) {
  107. // console.log(url, params)
  108. try {
  109. let response = await axiosservice({
  110. url,
  111. params,
  112. method: 'get',
  113. })
  114. return response.data
  115. } catch (err) {
  116. throw err
  117. }
  118. },
  119. async postJson(url, data) {
  120. try {
  121. let response = await axiosservice({
  122. url,
  123. data,
  124. method: 'post',
  125. })
  126. return response.data
  127. } catch (err) {
  128. throw err
  129. }
  130. },
  131. async fetchJson(url, params, data) {
  132. try {
  133. let response = await axiosservice({
  134. url,
  135. params,
  136. data,
  137. method: 'post',
  138. })
  139. return response
  140. } catch (err) {
  141. throw err
  142. }
  143. },
  144. async postupload(url, data) {
  145. try {
  146. let response = await axiosservice({
  147. url,
  148. data,
  149. method: 'post',
  150. headers: {
  151. 'Content-Type': 'multipart/form-data',
  152. },
  153. })
  154. return response.data
  155. } catch (err) {
  156. throw err
  157. }
  158. },
  159. download(url, requestData) {
  160. // 响应类型:arraybuffer, blob
  161. axiosservice
  162. .post(url, requestData, {
  163. responseType: 'blob',
  164. })
  165. .then((resp) => {
  166. let headers = resp.headers
  167. let contentType = headers['content-type']
  168. if (!resp.data) {
  169. console.error('响应异常:', resp)
  170. return false
  171. } else {
  172. //console.log("下载文件:", resp)
  173. const blob = new Blob([resp.data], {
  174. type: contentType,
  175. })
  176. const contentDisposition = resp.headers['content-disposition']
  177. let fileName = 'unknown'
  178. if (contentDisposition) {
  179. fileName = window.decodeURI(resp.headers['content-disposition'].split('=')[1])
  180. }
  181. downFile(blob, fileName)
  182. }
  183. })
  184. .catch(function(error) {})
  185. },
  186. axios: axiosservice,
  187. }