axios.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. // +---------------------------------------------------------------------
  2. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  3. // +---------------------------------------------------------------------
  4. // | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
  5. // +---------------------------------------------------------------------
  6. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  7. // +---------------------------------------------------------------------
  8. // | Author: CRMEB Team <admin@crmeb.com>
  9. // +---------------------------------------------------------------------
  10. import axios from 'axios';
  11. import store from '@/store';
  12. // import { Spin } from 'iview'
  13. const addErrorLog = (errorInfo) => {
  14. const {
  15. statusText,
  16. status,
  17. request: { responseURL },
  18. } = errorInfo;
  19. let info = {
  20. type: 'ajax',
  21. code: status,
  22. mes: statusText,
  23. url: responseURL,
  24. };
  25. if (!responseURL.includes('save_error_logger')) store.dispatch('addErrorLog', info);
  26. };
  27. class HttpRequest {
  28. constructor(baseUrl = baseURL) {
  29. this.baseUrl = 'http://admin.crmeb.net/adminapi';
  30. this.queue = {};
  31. }
  32. getInsideConfig() {
  33. const config = {
  34. baseURL: this.baseUrl,
  35. headers: {
  36. //
  37. },
  38. };
  39. return config;
  40. }
  41. destroy(url) {
  42. delete this.queue[url];
  43. if (!Object.keys(this.queue).length) {
  44. // Spin.hide()
  45. }
  46. }
  47. interceptors(instance, url) {
  48. // 请求拦截
  49. instance.interceptors.request.use(
  50. (config) => {
  51. // 添加全局的loading...
  52. if (!Object.keys(this.queue).length) {
  53. // Spin.show() // 不建议开启,因为界面不友好
  54. }
  55. this.queue[url] = true;
  56. return config;
  57. },
  58. (error) => {
  59. return Promise.reject(error);
  60. },
  61. );
  62. // 响应拦截
  63. instance.interceptors.response.use(
  64. (res) => {
  65. this.destroy(url);
  66. const { data, status } = res;
  67. return { data, status };
  68. },
  69. (error) => {
  70. this.destroy(url);
  71. let errorInfo = error.response;
  72. if (!errorInfo) {
  73. const {
  74. request: { statusText, status },
  75. config,
  76. } = JSON.parse(JSON.stringify(error));
  77. errorInfo = {
  78. statusText,
  79. status,
  80. request: { responseURL: config.url },
  81. };
  82. }
  83. addErrorLog(errorInfo);
  84. return Promise.reject(error);
  85. },
  86. );
  87. }
  88. request(options) {
  89. const instance = axios.create();
  90. options = Object.assign(this.getInsideConfig(), options);
  91. this.interceptors(instance, options.url);
  92. return instance(options);
  93. }
  94. }
  95. export default HttpRequest;