axios.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import axios from "axios";
  2. import { getToken } from "@/utils/storage/sessionToken";
  3. import { TOKEN } from "@/constant";
  4. import { loadingBar, message } from "@/plugin/naive-ui";
  5. // 显示消息
  6. const showMessage = (res) => {
  7. if (res.Code !== 200) {
  8. message.error(res.Msg);
  9. }
  10. };
  11. const service = axios.create({
  12. baseURL: import.meta.env.VITE_API_BASE_URL,
  13. timeout: 60000 * 15,
  14. });
  15. // 添加请求拦截器
  16. service.interceptors.request.use(
  17. function (config) {
  18. // 在发送请求之前做些什么
  19. loadingBar.start();
  20. if (config.url !== "/VerifyTemplateMapData/Pu") {
  21. const formData = new FormData();
  22. if (
  23. config.url !== "/Login_Admin_verification" &&
  24. config.url !== "/Login_verification"
  25. ) {
  26. const token = getToken();
  27. formData.append(TOKEN, token);
  28. }
  29. Object.entries(config.data).forEach(([key, value]) => {
  30. formData.append(key, value);
  31. });
  32. config.data = formData;
  33. }
  34. return config;
  35. },
  36. function (error) {
  37. // 对请求错误做些什么
  38. return Promise.reject(error);
  39. }
  40. );
  41. // 添加响应拦截器
  42. service.interceptors.response.use(
  43. function (response) {
  44. // 2xx 范围内的状态码都会触发该函数。
  45. // 对响应数据做点什么
  46. const { data: res } = response;
  47. showMessage(res);
  48. loadingBar.finish();
  49. return response;
  50. },
  51. function (error) {
  52. // 超出 2xx 范围的状态码都会触发该函数。
  53. // 对响应错误做点什么
  54. return Promise.reject(error);
  55. }
  56. );
  57. export default service;