request.js 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  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/ruoyi";
  7. import jsonlint from "@/utils/jsonlint";
  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: 60000,
  15. withCredentials: true,
  16. transformResponse: [function (data) {
  17. // Do whatever you want to transform the data
  18. if (typeof data === 'string') {
  19. try {
  20. data = jsonlint.parse(data);
  21. } catch (e) { /* Ignore */ }
  22. }
  23. return data;
  24. }]
  25. })
  26. // request拦截器
  27. service.interceptors.request.use(config => {
  28. // 是否需要设置 token
  29. const isToken = (config.headers || {}).isToken === false
  30. if (getToken() && !isToken) {
  31. config.headers['Authorization'] = 'Bearer ' + getToken(); // 让每个请求携带自定义token 请根据实际情况自行修改
  32. }
  33. if (store.getters && store.getters.name) {
  34. config.headers['userName'] = store.getters.name; // 让每个请求携带userName 请根据实际情况自行修改
  35. }
  36. // get请求映射params参数
  37. if (config.method === 'get' && config.params) {
  38. let url = config.url + '?';
  39. for (const propName of Object.keys(config.params)) {
  40. const value = config.params[propName];
  41. var part = encodeURIComponent(propName) + "=";
  42. if (value !== null && typeof(value) !== "undefined") {
  43. if (typeof value === 'object') {
  44. for (const key of Object.keys(value)) {
  45. let params = propName + '[' + key + ']';
  46. var subPart = encodeURIComponent(params) + "=";
  47. url += subPart + encodeURIComponent(value[key]) + "&";
  48. }
  49. } else {
  50. url += part + encodeURIComponent(value) + "&";
  51. }
  52. }
  53. }
  54. url = url.slice(0, -1);
  55. config.params = {};
  56. config.url = url;
  57. }
  58. return config
  59. }, error => {
  60. console.log(error)
  61. Promise.reject(error)
  62. })
  63. // 响应拦截器
  64. service.interceptors.response.use(res => {
  65. // 未设置状态码则默认成功状态
  66. const code = res.data.code || 200;
  67. // 获取错误信息
  68. const msg = errorCode[code] || res.data.msg || errorCode['default']
  69. if (code === 401) {
  70. MessageBox.confirm('登录状态已过期,您可以继续留在该页面,或者重新登录', '系统提示', {
  71. confirmButtonText: '重新登录',
  72. cancelButtonText: '取消',
  73. type: 'warning'
  74. }
  75. ).then(() => {
  76. store.dispatch('LogOut').then(() => {
  77. location.href = '/index';
  78. })
  79. }).catch(() => {});
  80. } else if (code === 500) {
  81. Message({
  82. message: msg,
  83. type: 'error'
  84. })
  85. return Promise.reject(new Error(msg))
  86. } else if (code !== 200) {
  87. Notification.error({
  88. title: msg
  89. })
  90. return Promise.reject('error')
  91. } else {
  92. return res.data
  93. }
  94. },
  95. error => {
  96. console.log('err' + error)
  97. let { message } = error;
  98. if (message == "Network Error") {
  99. message = "后端接口连接异常";
  100. }
  101. else if (message.includes("timeout")) {
  102. message = "系统接口请求超时";
  103. }
  104. else if (message.includes("Request failed with status code")) {
  105. message = "系统接口" + message.substr(message.length - 3) + "异常";
  106. }
  107. Message({
  108. message: message,
  109. type: 'error',
  110. duration: 5 * 1000
  111. })
  112. return Promise.reject(error)
  113. }
  114. )
  115. // 通用下载方法
  116. export function download(url, params, filename) {
  117. return service.post(url, params, {
  118. transformRequest: [(params) => {
  119. return tansParams(params)
  120. }],
  121. headers: {
  122. 'Content-Type': 'application/x-www-form-urlencoded'
  123. },
  124. responseType: 'blob'
  125. }).then((data) => {
  126. const content = data
  127. const blob = new Blob([content])
  128. if ('download' in document.createElement('a')) {
  129. const elink = document.createElement('a')
  130. elink.download = filename
  131. elink.style.display = 'none'
  132. elink.href = URL.createObjectURL(blob)
  133. document.body.appendChild(elink)
  134. elink.click()
  135. URL.revokeObjectURL(elink.href)
  136. document.body.removeChild(elink)
  137. } else {
  138. navigator.msSaveBlob(blob, filename)
  139. }
  140. }).catch((r) => {
  141. console.error(r)
  142. })
  143. }
  144. export default service