request.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import axios from "axios";
  2. import { showMessage } from "./errorStatusCode"; // 引入状态码文件
  3. import type { AxiosRequestConfig, AxiosResponse, AxiosError } from "axios";
  4. import { ElNotification } from "element-plus";
  5. const baseURL = "/api";
  6. // 创建axios实例
  7. const instance = axios.create({
  8. baseURL, // 设置API的基础URL
  9. });
  10. // 请求拦截器
  11. instance.interceptors.request.use(
  12. (config: AxiosRequestConfig): any => {
  13. // 可在请求发送前对config进行修改,如添加请求头等
  14. const headers = config.headers || {};
  15. headers["Authorization"] = "Bxxx";
  16. config.headers = headers;
  17. return config;
  18. },
  19. (error: AxiosError) => {
  20. // 处理请求错误
  21. return Promise.reject(error);
  22. }
  23. );
  24. // 响应拦截器
  25. instance.interceptors.response.use(
  26. (response: AxiosResponse) => {
  27. // 对响应数据进行处理
  28. if (response.status != 200) {
  29. ElNotification({
  30. message: showMessage(response.status), // 传入响应码,匹配响应码对应信息,
  31. type: "error",
  32. });
  33. }
  34. return response;
  35. },
  36. (error: AxiosError) => {
  37. // 处理响应错误
  38. return Promise.reject(error);
  39. }
  40. );
  41. // 封装GET请求
  42. export async function get(url: string, params?: any): Promise<any> {
  43. return instance
  44. .get(url, { params })
  45. .then((response) => response.data)
  46. .catch((error) => {
  47. throw error;
  48. });
  49. }
  50. // 封装POST请求
  51. export async function post(url: string, data?: any): Promise<any> {
  52. return instance
  53. .post(url, data, {
  54. headers: {
  55. "Content-type": " application/x-www-form-urlencoded; charset=UTF-8",
  56. },
  57. })
  58. .then((response) => response.data)
  59. .catch((error) => {
  60. throw error;
  61. });
  62. }