request.js 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. import axios from 'axios'
  2. import { Notification, MessageBox, Message } from 'element-ui'
  3. import store from '@/store'
  4. import { getToken } from '@/utils/auth'
  5. import errorCode from '@/utils/errorCode'
  6. import { tansParams } from "@/utils/huyi";
  7. import { getRepeatToken } from "@/utils/common";
  8. axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
  9. // 创建axios实例
  10. const service = axios.create({
  11. // axios中请求配置有baseURL选项,表示请求URL公共部分
  12. baseURL: process.env.VUE_APP_BASE_API,
  13. // 超时
  14. timeout: 10000
  15. })
  16. const repeatToken = getRepeatToken();
  17. // request拦截器
  18. service.interceptors.request.use(config => {
  19. // 是否需要设置 token
  20. const isToken = (config.headers || {}).isToken === false
  21. if (getToken() && !isToken) {
  22. config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  23. }
  24. const repeat = config.repeat;
  25. if (repeat) {
  26. config.headers['repeatToken'] = repeatToken + ":" + config.url;
  27. }
  28. // get请求映射params参数
  29. if (config.method === 'get' && config.params) {
  30. let url = config.url + '?';
  31. for (const propName of Object.keys(config.params)) {
  32. const value='';
  33. if(typeof(config.params[propName])=="string"){
  34. value = config.params[propName].trim();
  35. }else{
  36. value= config.params[propName];
  37. }
  38. var part = encodeURIComponent(propName) + "=";
  39. if (value && typeof(value) !== "undefined") {
  40. if (typeof value === 'object') {
  41. for (const key of Object.keys(value)) {
  42. let params = propName + '[' + key + ']';
  43. var subPart = encodeURIComponent(params) + "=";
  44. url += subPart + encodeURIComponent(value[key]) + "&";
  45. }
  46. } else {
  47. url += part + encodeURIComponent(value) + "&";
  48. }
  49. }
  50. }
  51. url = url.slice(0, -1);
  52. config.params = {};
  53. config.url = url;
  54. }else if(config.method === 'post' && config.data){
  55. // console.log(Object.keys(config.data))
  56. // console.log(typeof(config.data));
  57. if(typeof(config.data)=== 'object'){
  58. for (const propName of Object.keys(config.data)) {
  59. if(config.data[propName]){
  60. if(typeof(config.data[propName])=="string"){
  61. config.data[propName] = config.data[propName].trim();
  62. }
  63. }
  64. }
  65. }
  66. }
  67. return config
  68. }, error => {
  69. console.log(error)
  70. Promise.reject(error)
  71. })
  72. // 响应拦截器
  73. service.interceptors.response.use(res => {
  74. // 未设置状态码则默认成功状态
  75. const code = res.data.code || 200;
  76. // 获取错误信息
  77. const msg = errorCode[code] || res.data.msg || errorCode['default']
  78. if (code === 401) {
  79. MessageBox.confirm('登录状态已过期,您可以继续留在该页面,或者重新登录', '系统提示', {
  80. confirmButtonText: '重新登录',
  81. cancelButtonText: '取消',
  82. type: 'warning'
  83. }
  84. ).then(() => {
  85. store.dispatch('LogOut').then(() => {
  86. location.href = '/home';
  87. })
  88. })
  89. } else if (code === 500) {
  90. Message({
  91. message: msg,
  92. type: 'error'
  93. })
  94. return Promise.reject(new Error(msg))
  95. } else if (code === 501) {
  96. MessageBox.confirm('您的账号已在其他地方登录,请重新登录!', '系统提示', {
  97. confirmButtonText: '重新登录',
  98. cancelButtonText: '取消',
  99. type: 'warning'
  100. }
  101. ).then(() => {
  102. store.dispatch('LogOut').then(() => {
  103. location.href = '/home';
  104. })
  105. })
  106. return res.data;
  107. } else if (code !== 200) {
  108. Notification.error({
  109. title: msg
  110. })
  111. return Promise.reject('error')
  112. } else {
  113. return res.data
  114. }
  115. },
  116. error => {
  117. console.log('err' + error)
  118. let { message } = error;
  119. if (message == "Network Error") {
  120. message = "后端接口连接异常";
  121. }
  122. else if (message.includes("timeout")) {
  123. message = "系统接口请求超时";
  124. }
  125. else if (message.includes("Request failed with status code")) {
  126. message = "系统接口" + message.substr(message.length - 3) + "异常";
  127. }
  128. Message({
  129. message: message,
  130. type: 'error',
  131. duration: 5 * 1000
  132. })
  133. return Promise.reject(error)
  134. }
  135. )
  136. // 通用下载方法
  137. export function download(url, params, filename) {
  138. return service.post(url, params, {
  139. transformRequest: [(params) => {
  140. return tansParams(params)
  141. }],
  142. headers: {
  143. 'Content-Type': 'application/x-www-form-urlencoded'
  144. },
  145. responseType: 'blob'
  146. }).then((data) => {
  147. const content = data
  148. const blob = new Blob([content])
  149. if ('download' in document.createElement('a')) {
  150. const elink = document.createElement('a')
  151. elink.download = filename
  152. elink.style.display = 'none'
  153. elink.href = URL.createObjectURL(blob)
  154. document.body.appendChild(elink)
  155. elink.click()
  156. URL.revokeObjectURL(elink.href)
  157. document.body.removeChild(elink)
  158. } else {
  159. navigator.msSaveBlob(blob, filename)
  160. }
  161. }).catch((r) => {
  162. console.error(r)
  163. })
  164. }
  165. export default service