request.ts 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  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. import { useStore } from "../store/index";
  6. const baseURL = "/api";
  7. // 创建axios实例
  8. const instance = axios.create({
  9. baseURL, // 设置API的基础URL
  10. });
  11. // 请求拦截器
  12. instance.interceptors.request.use(
  13. (config: AxiosRequestConfig): any => {
  14. // 可在请求发送前对config进行修改,如添加请求头等
  15. const { getToken } = useStore();
  16. const token = getToken;
  17. const headers = config.headers || {};
  18. headers["Token"] = token;
  19. config.headers = headers;
  20. return config;
  21. },
  22. (error: AxiosError) => {
  23. // 处理请求错误
  24. return Promise.reject(error);
  25. }
  26. );
  27. // 响应拦截器
  28. instance.interceptors.response.use(
  29. (response: AxiosResponse) => {
  30. // 对响应数据进行处理
  31. if (response.status != 200) {
  32. ElNotification({
  33. message: showMessage(response.status), // 传入响应码,匹配响应码对应信息,
  34. type: "error",
  35. });
  36. }
  37. return response;
  38. },
  39. (error: AxiosError) => {
  40. // 处理响应错误
  41. return Promise.reject(error);
  42. }
  43. );
  44. // 封装GET请求
  45. export async function get(url: string, params?: any, file: boolean = false): Promise<any> {
  46. return new Promise((resolve, reject) => {
  47. instance
  48. .get(url, { params })
  49. .then(({ data }: any) => {
  50. const { code } = data;
  51. if (code === "ok" || file) {
  52. resolve(data);
  53. return;
  54. }
  55. reject(data);
  56. })
  57. .catch((error) => {
  58. reject(error);
  59. });
  60. });
  61. }
  62. // 封装POST请求
  63. export async function post(url: string, data?: any): Promise<any> {
  64. return new Promise((resolve, reject) => {
  65. instance
  66. .post(url, data, {
  67. headers: {
  68. "Content-type": " application/x-www-form-urlencoded; charset=UTF-8",
  69. },
  70. })
  71. .then(({ data }: any) => {
  72. const { code } = data;
  73. if (code === "ok") {
  74. resolve(data);
  75. return;
  76. }
  77. reject(data);
  78. })
  79. .catch((error) => {
  80. reject(error);
  81. });
  82. });
  83. }
  84. // 封装文件上传请求
  85. export async function uploadFile(url: string, data?: any): Promise<any> {
  86. return new Promise((resolve, reject) => {
  87. instance
  88. .post(url, data, {
  89. headers: {
  90. "Content-type": "multipart/form-data",
  91. },
  92. })
  93. .then(({ data }: any) => {
  94. const { code } = data;
  95. if (code === "ok") {
  96. resolve(data);
  97. return;
  98. }
  99. reject(data);
  100. })
  101. .catch((error) => {
  102. reject(error);
  103. });
  104. });
  105. }