http.ts 2.4 KB

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