http.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. "use strict";
  2. import axios from "axios";
  3. import { Toast } from "vant";
  4. // Full config: https://github.com/axios/axios#request-config
  5. // axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
  6. // axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
  7. // axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
  8. // 请求数
  9. let LOADINGCOUNT = 0;
  10. let LOADING;
  11. let config = {
  12. baseURL: import.meta.env.VITE_APP_SSBG_BASEAPIURL,
  13. timeout: 60 * 1000, // Timeout
  14. // withCredentials: true, // Check cross-site Access-Control
  15. };
  16. const _axios = axios.create(config);
  17. _axios.interceptors.request.use(
  18. function (config) {
  19. // Do something before request is sent
  20. // 设置loading
  21. if (LOADINGCOUNT === 0) {
  22. LOADING = Toast.loading({
  23. message: "loading...",
  24. duration: 0,
  25. forbidClick: true,
  26. });
  27. }
  28. LOADINGCOUNT++;
  29. config.headers.Authorization = localStorage.getItem('ssbg-token') || '';
  30. return config;
  31. },
  32. function (error) {
  33. // Do something with request error
  34. return Promise.reject(error);
  35. }
  36. );
  37. // Add a response interceptor
  38. _axios.interceptors.response.use(
  39. function (response) {
  40. // Do something with response data
  41. //关闭loading
  42. LOADINGCOUNT--;
  43. if (LOADINGCOUNT === 0) {
  44. LOADING.clear();
  45. }
  46. return response.data;
  47. },
  48. function (error) {
  49. LOADING.clear();
  50. // Do something with response error
  51. return Promise.reject(error);
  52. }
  53. );
  54. /**
  55. * 导出get请求方法
  56. * @url 请求地址
  57. * @params get请求参数
  58. */
  59. export const get = (url, params) => {
  60. return _axios.get(url, { params });
  61. };
  62. /**
  63. * 导出post请求方法
  64. * @url 请求地址
  65. * @params post请求参数
  66. */
  67. export const post = (url, params) => {
  68. return _axios.post(url, params);
  69. };