index.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. "use strict";
  2. import axios from "axios";
  3. import router from "@/router";
  4. import CryptoJS from '@/utils/crypto'
  5. import { ElMessage } from 'element-plus'
  6. // Full config: https://github.com/axios/axios#request-config
  7. // axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
  8. // axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
  9. // axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
  10. let config = {
  11. baseURL: import.meta.env.VITE_APP_API_URL,
  12. timeout: 10*60 * 1000, // Timeout
  13. // withCredentials: true, // Check cross-site Access-Control
  14. };
  15. const _axios = axios.create(config);
  16. _axios.interceptors.request.use(
  17. function (config) {
  18. // Do something before request is sent
  19. let auth = localStorage.getItem('token')
  20. if(auth) {
  21. config.headers.Authorization = auth;
  22. }
  23. // config.headers.Authorization=localStorage.getItem('token')||''
  24. // 检查请求路径并设置responseType
  25. if (config.url.endsWith('/user/potential/export/excel')) {
  26. config.responseType = 'blob'; // 如果是导出excel的请求,则设置responseType为blob
  27. }
  28. return config;
  29. },
  30. function (error) {
  31. // Do something with request error
  32. return Promise.reject(error);
  33. }
  34. );
  35. // Add a response interceptor
  36. _axios.interceptors.response.use(
  37. function (response) {
  38. // Do something with response data
  39. let data
  40. // 如果是是导出excel的请求,则不进行解密操作
  41. if(import.meta.env.MODE==='production' && !response.config.url.endsWith('/user/potential/export/excel')){
  42. data=JSON.parse(CryptoJS.Des3Decrypt(response.data,import.meta.env.VITE_APP_RESPONSE_DES_KEY));//解密
  43. }else{
  44. data=response.data
  45. }
  46. if(response.status!==200){
  47. setTimeout(() => {
  48. ElMessage.error('网络异常')
  49. }, 100);
  50. }
  51. if(!data){
  52. setTimeout(() => {
  53. ElMessage.error('服务器开了个小差')
  54. }, 100);
  55. }
  56. if(data.Ret===408){//token失效
  57. ElMessage.error(data.Msg)
  58. router.replace('/login')
  59. }
  60. if(data.Ret===403){
  61. setTimeout(() => {
  62. ElMessage.error(data.Msg||'网络异常')
  63. }, 100);
  64. }
  65. return data;
  66. },
  67. function (error) {
  68. console.log(error);
  69. ElMessage.error(error.message)
  70. // Do something with response error
  71. return Promise.reject(error);
  72. }
  73. );
  74. /**
  75. * 导出get请求方法
  76. * @url 请求地址
  77. * @params get请求参数
  78. */
  79. export const get = (url, params) => {
  80. return _axios.get(url, { params });
  81. };
  82. /**
  83. * 导出post请求方法
  84. * @url 请求地址
  85. * @params post请求参数
  86. */
  87. export const post = (url, params) => {
  88. return _axios.post(url, params);
  89. };