request.js 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  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 Cookies from "js-cookie";
  7. import {getTenantEnable} from "@/utils/ruoyi";
  8. // 是否显示重新登录
  9. let isReloginShow;
  10. axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
  11. // 创建axios实例
  12. const service = axios.create({
  13. // axios中请求配置有baseURL选项,表示请求URL公共部分
  14. baseURL: process.env.VUE_APP_BASE_API + '/admin-api/', // 此处的 /admin-api/ 地址,原因是后端的基础路径为 /admin-api/
  15. // 超时
  16. timeout: 10000
  17. })
  18. // request拦截器
  19. service.interceptors.request.use(config => {
  20. // 是否需要设置 token
  21. const isToken = (config.headers || {}).isToken === false
  22. if (getToken() && !isToken) {
  23. config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  24. }
  25. // 设置租户
  26. if (getTenantEnable()) {
  27. const tenantId = Cookies.get('tenantId');
  28. if (tenantId) {
  29. config.headers['tenant-id'] = tenantId;
  30. }
  31. }
  32. // get请求映射params参数
  33. if (config.method === 'get' && config.params) {
  34. let url = config.url + '?';
  35. for (const propName of Object.keys(config.params)) {
  36. const value = config.params[propName];
  37. var part = encodeURIComponent(propName) + "=";
  38. if (value !== null && typeof(value) !== "undefined") {
  39. if (typeof value === 'object') {
  40. for (const key of Object.keys(value)) {
  41. let params = propName + '[' + key + ']';
  42. var subPart = encodeURIComponent(params) + "=";
  43. url += subPart + encodeURIComponent(value[key]) + "&";
  44. }
  45. } else {
  46. url += part + encodeURIComponent(value) + "&";
  47. }
  48. }
  49. }
  50. url = url.slice(0, -1);
  51. config.params = {};
  52. config.url = url;
  53. }
  54. return config
  55. }, error => {
  56. console.log(error)
  57. Promise.reject(error)
  58. })
  59. // 响应拦截器
  60. service.interceptors.response.use(res => {
  61. // 未设置状态码则默认成功状态
  62. const code = res.data.code || 200;
  63. // 获取错误信息
  64. const msg = errorCode[code] || res.data.msg || errorCode['default']
  65. if (code === 401) {
  66. if (!isReloginShow) {
  67. isReloginShow = true;
  68. MessageBox.confirm('登录状态已过期,您可以继续留在该页面,或者重新登录', '系统提示', {
  69. confirmButtonText: '重新登录',
  70. cancelButtonText: '取消',
  71. type: 'warning'
  72. }
  73. ).then(() => {
  74. isReloginShow = false;
  75. store.dispatch('LogOut').then(() => {
  76. // 如果是登录页面不需要重新加载
  77. if (window.location.hash.indexOf("#/login") !== 0) {
  78. location.href = '/index';
  79. }
  80. })
  81. }).catch(() => {
  82. isReloginShow = false;
  83. });
  84. }
  85. return Promise.reject('无效的会话,或者会话已过期,请重新登录。')
  86. } else if (code === 500) {
  87. Message({
  88. message: msg,
  89. type: 'error'
  90. })
  91. return Promise.reject(new Error(msg))
  92. } else if (code === 901) {
  93. Message({
  94. type: 'error',
  95. duration: 0,
  96. dangerouslyUseHTMLString: true,
  97. message: '<div>演示模式,无法进行写操作</div>'
  98. + '<div> &nbsp; </div>'
  99. + '<div>参考 https://doc.iocoder.cn/ 教程</div>'
  100. + '<div> &nbsp; </div>'
  101. + '<div>5 分钟搭建本地环境</div>',
  102. })
  103. return Promise.reject(new Error(msg))
  104. } else if (code !== 200) {
  105. Notification.error({
  106. title: msg
  107. })
  108. return Promise.reject('error')
  109. } else {
  110. return res.data
  111. }
  112. },
  113. error => {
  114. console.log('err' + error)
  115. let { message } = error;
  116. if (message === "Network Error") {
  117. message = "后端接口连接异常";
  118. }
  119. else if (message.includes("timeout")) {
  120. message = "系统接口请求超时";
  121. }
  122. else if (message.includes("Request failed with status code")) {
  123. message = "系统接口" + message.substr(message.length - 3) + "异常";
  124. }
  125. Message({
  126. message: message,
  127. type: 'error',
  128. duration: 5 * 1000
  129. })
  130. return Promise.reject(error)
  131. }
  132. )
  133. export function getBaseHeader() {
  134. return {
  135. 'Authorization': "Bearer " + getToken(),
  136. 'tenant-id': Cookies.get('tenantId'),
  137. }
  138. }
  139. export default service