http.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import { MessagePlugin } from 'tdesign-vue-next';
  2. import axios from 'axios';
  3. import { getCookie } from '@/services/cookie';
  4. import router from './router';
  5. import i18n from './i18n';
  6. const $t = i18n.global.t;
  7. // axios 配置
  8. axios.defaults.timeout = 60000;
  9. axios.defaults.withCredentials = false;
  10. // http request 拦截器
  11. axios.interceptors.request.use(
  12. (config: any) => {
  13. config.headers.Authorization =
  14. 'Bearer ' + ( getCookie('token') || new URLSearchParams(location.search).get('token') || '');
  15. return config;
  16. },
  17. (err: any) => Promise.reject(err)
  18. );
  19. // http response 拦截器
  20. axios.interceptors.response.use(
  21. (response: any) => {
  22. if (response && response.data && response.data.error) {
  23. MessagePlugin.error(response.data.error);
  24. return;
  25. }
  26. if (response) {
  27. if (response.status == undefined) {
  28. return response;
  29. }
  30. return response.data;
  31. }
  32. return;
  33. },
  34. (error: any) => {
  35. if (error && !error.response) {
  36. return;
  37. }
  38. if (error && error.response) {
  39. if (
  40. error.response.config.url === '/api/account/profile' ||
  41. error.response.data.error === $t('此为付费数据,请购买后访问')
  42. ) {
  43. return;
  44. }
  45. if (
  46. error.response.status !== 401 &&
  47. error.response &&
  48. error.response.data &&
  49. error.response.data.error
  50. ) {
  51. MessagePlugin.error(error.response.data.error);
  52. return;
  53. }
  54. switch (error.response.status) {
  55. case 401:
  56. if (error.response.config.url==='/api/account/statistics') {
  57. break;
  58. }
  59. sessionStorage.setItem('cb', encodeURIComponent(location.href));
  60. MessagePlugin.error($t('请先登录!'));
  61. // router.replace({ path: '/login' });
  62. break;
  63. case 403:
  64. MessagePlugin.error($t('请求错误,不合法的请求!'));
  65. break;
  66. case 404:
  67. if (error.response.config.url.indexOf('/data/') !== 0) {
  68. MessagePlugin.error($t('访问数据不存在,请检查后重试!'));
  69. }
  70. break;
  71. case 500:
  72. MessagePlugin.error($t('请求服务错误,请稍后重试!'));
  73. break;
  74. case 504:
  75. MessagePlugin.error($t('网络超时,请检测你的网络!'));
  76. break;
  77. default:
  78. MessagePlugin.error($t('未知网络错误!'));
  79. break;
  80. }
  81. }
  82. // return error.response ? error.response.data : error;
  83. }
  84. );
  85. export default axios;