axios.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. const addErrorLog = (errorInfo) => {
  13. const {
  14. statusText,
  15. status,
  16. request: { responseURL },
  17. } = errorInfo;
  18. let info = {
  19. type: 'ajax',
  20. code: status,
  21. mes: statusText,
  22. url: responseURL,
  23. };
  24. if (!responseURL.includes('save_error_logger')) store.dispatch('addErrorLog', info);
  25. };
  26. class HttpRequest {
  27. constructor(baseUrl = baseURL) {
  28. this.baseUrl = 'http://admin.crmeb.net/adminapi';
  29. this.queue = {};
  30. }
  31. getInsideConfig() {
  32. const config = {
  33. baseURL: this.baseUrl,
  34. headers: {
  35. //
  36. },
  37. };
  38. return config;
  39. }
  40. destroy(url) {
  41. delete this.queue[url];
  42. if (!Object.keys(this.queue).length) {
  43. }
  44. }
  45. interceptors(instance, url) {
  46. // 请求拦截
  47. instance.interceptors.request.use(
  48. (config) => {
  49. // 添加全局的loading...
  50. if (!Object.keys(this.queue).length) {
  51. // Spin.show() // 不建议开启,因为界面不友好
  52. }
  53. this.queue[url] = true;
  54. return config;
  55. },
  56. (error) => {
  57. return Promise.reject(error);
  58. },
  59. );
  60. // 响应拦截
  61. instance.interceptors.response.use(
  62. (res) => {
  63. this.destroy(url);
  64. const { data, status } = res;
  65. return { data, status };
  66. },
  67. (error) => {
  68. this.destroy(url);
  69. let errorInfo = error.response;
  70. if (!errorInfo) {
  71. const {
  72. request: { statusText, status },
  73. config,
  74. } = JSON.parse(JSON.stringify(error));
  75. errorInfo = {
  76. statusText,
  77. status,
  78. request: { responseURL: config.url },
  79. };
  80. }
  81. addErrorLog(errorInfo);
  82. return Promise.reject(error);
  83. },
  84. );
  85. }
  86. request(options) {
  87. const instance = axios.create();
  88. options = Object.assign(this.getInsideConfig(), options);
  89. this.interceptors(instance, options.url);
  90. return instance(options);
  91. }
  92. }
  93. export default HttpRequest;