request.js 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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: 20000
  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 === 502) {
  108. MessageBox.confirm('您的账号企业权限发生变化,请重新登录!', '系统提示', {
  109. confirmButtonText: '重新登录',
  110. cancelButtonText: '取消',
  111. type: 'warning'
  112. }
  113. ).then(() => {
  114. store.dispatch('LogOut').then(() => {
  115. location.href = '/home';
  116. })
  117. })
  118. return res.data;
  119. } else if (code === 503) {
  120. MessageBox.confirm('用户角色更变,请重新登录!', '系统提示', {
  121. confirmButtonText: '重新登录',
  122. cancelButtonText: '取消',
  123. type: 'warning'
  124. }
  125. ).then(() => {
  126. store.dispatch('LogOut').then(() => {
  127. location.href = '/home';
  128. })
  129. })
  130. return res.data;
  131. } else if (code !== 200) {
  132. Notification.error({
  133. title: msg
  134. })
  135. return Promise.reject('error')
  136. } else {
  137. return res.data
  138. }
  139. },
  140. error => {
  141. console.log('err' + error)
  142. let { message } = error;
  143. if (message == "Network Error") {
  144. message = "后端接口连接异常";
  145. }
  146. else if (message.includes("timeout")) {
  147. message = "系统接口请求超时";
  148. }
  149. else if (message.includes("Request failed with status code")) {
  150. message = "系统接口" + message.substr(message.length - 3) + "异常";
  151. }
  152. Message({
  153. message: message,
  154. type: 'error',
  155. duration: 5 * 1000
  156. })
  157. return Promise.reject(error)
  158. }
  159. )
  160. // 通用下载方法
  161. export function download(url, params, filename) {
  162. return service.post(url, params, {
  163. transformRequest: [(params) => {
  164. return tansParams(params)
  165. }],
  166. headers: {
  167. 'Content-Type': 'application/x-www-form-urlencoded'
  168. },
  169. responseType: 'blob'
  170. }).then((data) => {
  171. const content = data
  172. const blob = new Blob([content])
  173. if ('download' in document.createElement('a')) {
  174. const elink = document.createElement('a')
  175. elink.download = filename
  176. elink.style.display = 'none'
  177. elink.href = URL.createObjectURL(blob)
  178. document.body.appendChild(elink)
  179. elink.click()
  180. URL.revokeObjectURL(elink.href)
  181. document.body.removeChild(elink)
  182. } else {
  183. navigator.msSaveBlob(blob, filename)
  184. }
  185. }).catch((r) => {
  186. console.error(r)
  187. })
  188. }
  189. export default service