request.js 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  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 !==
  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. // console.log('进入403')
  110. // console.log('进入403token',getToken())
  111. vue.$message.error(`登录过期,请重新登录!`);
  112. removeToken();
  113. console.log('清空之后的tocken',getToken())
  114. await store.dispatch("user/resetToken").then(() => {
  115. setTimeout(async () => {
  116. location.reload();
  117. }, 1000);
  118. });
  119. return;
  120. }
  121. if (data.code == 404) {
  122. router.push("/404");
  123. }
  124. if (
  125. (data.code < 200 && data.code != 100) ||
  126. (data.code >= 300 && data.code != 100)
  127. ) {
  128. // Message({
  129. // message: data.msg || `请求失败code码为${ data.code }`,
  130. // type: 'error',
  131. // duration: 5 * 1000
  132. // })
  133. let str = data.msg || `请求失败code码为${data.code}`;
  134. vue.$message.error(str);
  135. return Promise.reject(new Error(data.msg || "Error"));
  136. } else {
  137. return data;
  138. }
  139. } else {
  140. return Promise.reject();
  141. }
  142. },
  143. async error => {
  144. if (error.message == "Network Error") {
  145. vue.$message.error("网络异常,请检查网络连接");
  146. } else {
  147. vue.$message.error(error.message);
  148. }
  149. await tryHideFullScreenLoading(store);
  150. return Promise.reject(error);
  151. }
  152. );
  153. export default service;