request.js 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. import ElementUI from "element-ui";
  2. import axios from "axios";
  3. import { Message } from "element-ui";
  4. import store from "@/store";
  5. import { getToken, removeToken, setToken } from "@/utils/auth";
  6. import cleanDeep from "clean-deep";
  7. import qs from "querystring";
  8. // import { Loading } from 'element-ui'
  9. import {
  10. showFullScreenLoading,
  11. tryHideFullScreenLoading
  12. } from "./request-loading";
  13. import router from "@/router/index";
  14. import Vue from "vue";
  15. const showMessage = Symbol("showMessage");
  16. class DonMessage {
  17. success(options, single = true) {
  18. this[showMessage]("success", options, single);
  19. }
  20. warning(options, single = true) {
  21. this[showMessage]("warning", options, single);
  22. }
  23. info(options, single = true) {
  24. this[showMessage]("info", options, single);
  25. }
  26. error(options, single = true) {
  27. this[showMessage]("error", options, single);
  28. }
  29. [showMessage](type, options, single) {
  30. if (single) {
  31. // 判断是否已存在Message
  32. if (document.getElementsByClassName("el-message").length === 0) {
  33. Message[type](options);
  34. }
  35. } else {
  36. Message[type](options);
  37. }
  38. }
  39. }
  40. Vue.use(ElementUI);
  41. // 命名根据需要,DonMessage只是在文章中使用
  42. Vue.prototype.$message = new DonMessage();
  43. let vue = new Vue();
  44. // let loading //定义loading变量
  45. // function startLoading () { //使用Element loading-start 方法
  46. // loading = Loading.service({
  47. // lock: true,
  48. // fullscreen: true,
  49. // text: '加载中……',
  50. // background: 'rgba(0, 0, 0, 0.7)'
  51. // })
  52. // }
  53. // function endLoading () {
  54. // //使用Element loading-close 方法
  55. // loading.close();
  56. // }
  57. //那么 showFullScreenLoading() tryHideFullScreenLoading() 要干的事儿就是将同一时刻的请求合并。
  58. //声明一个变量 needLoadingRequestCount,每次调用showFullScreenLoading方法 needLoadingRequestCount + 1。
  59. //调用tryHideFullScreenLoading()方法,needLoadingRequestCount - 1。needLoadingRequestCount为 0 时,结束 loading。
  60. // axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
  61. // create an axios instance
  62. const service = axios.create({
  63. baseURL: "", // url = base url + request url
  64. // withCredentials: true, // send cookies when cross-domain requests
  65. timeout: 180000 // request timeout
  66. });
  67. // { fullscreen: true, text: '努力加载中', spinner: 'el-icon-loading' }
  68. // request interceptor
  69. service.interceptors.request.use(
  70. async config => {
  71. // do something before request is sent
  72. await showFullScreenLoading(store);
  73. if (store.getters.token) {
  74. // let each request carry token
  75. // ['X-Token'] is a custom headers key
  76. // please modify it according to the actual situation
  77. config.headers["Authorization"] = getToken();
  78. // config.headers['content-type'] = "application/x-www-form-urlencoded"
  79. }
  80. let tenantConfig = sessionStorage.getItem("tenantConfig");
  81. tenantConfig = tenantConfig ? JSON.parse(tenantConfig) : {};
  82. if (tenantConfig.tenantId && tenantConfig.tenantId != "undefined") {
  83. config.headers["tenantId"] = tenantConfig.tenantId;
  84. }
  85. config.params = cleanDeep(config.params);
  86. // params: cleanDeep(options.params),
  87. // (config)
  88. return config;
  89. },
  90. error => {
  91. // do something with request error
  92. return Promise.reject(error);
  93. }
  94. );
  95. // response interceptor
  96. service.interceptors.response.use(
  97. async res => {
  98. //res.code !== 200
  99. await tryHideFullScreenLoading(store);
  100. if (res.data.code) {
  101. let data = JSON.parse(JSON.stringify(res.data));
  102. // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
  103. if (data.code == 401 || data.code == 403) {
  104. // Message({
  105. // message: `登录过期,请重新登录!`,
  106. // type: 'error',
  107. // duration: 5 * 1000
  108. // })
  109. vue.$message.error(`登录过期,请重新登录!`);
  110. removeToken();
  111. setToken("");
  112. await store.dispatch("user/resetToken").then(() => {
  113. setTimeout(async () => {
  114. location.reload();
  115. }, 1000);
  116. });
  117. return;
  118. }
  119. if (data.code == 404) {
  120. router.push("/404");
  121. }
  122. if (
  123. (data.code < 200 && data.code != 100) ||
  124. (data.code >= 300 && data.code != 100)
  125. ) {
  126. // Message({
  127. // message: data.msg || `请求失败code码为${ data.code }`,
  128. // type: 'error',
  129. // duration: 5 * 1000
  130. // })
  131. let str = data.msg || `请求失败code码为${data.code}`;
  132. vue.$message.error(str);
  133. return Promise.reject(new Error(data.msg || "Error"));
  134. } else {
  135. return data;
  136. }
  137. } else {
  138. return Promise.reject();
  139. }
  140. },
  141. async error => {
  142. if (error.message == "Network Error") {
  143. vue.$message.error("网络异常,请检查网络连接");
  144. } else {
  145. vue.$message.error(error.message);
  146. }
  147. await tryHideFullScreenLoading(store);
  148. return Promise.reject(error);
  149. }
  150. );
  151. export default service;