request.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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): Promise<any> {
  46. return instance
  47. .get(url, { params })
  48. .then((response) => response.data)
  49. .catch((error) => {
  50. throw error;
  51. });
  52. }
  53. // 封装POST请求
  54. export async function post(url: string, data?: any): Promise<any> {
  55. return instance
  56. .post(url, data, {
  57. headers: {
  58. "Content-type": " application/x-www-form-urlencoded; charset=UTF-8",
  59. },
  60. })
  61. .then((response) => response.data)
  62. .catch((error) => {
  63. throw error;
  64. });
  65. }
  66. // 封装文件上传请求
  67. export async function uploadFile(url: string, data?: any): Promise<any> {
  68. return instance
  69. .post(url, data, {
  70. headers: {
  71. "Content-type": "multipart/form-data",
  72. },
  73. })
  74. .then((response) => response.data)
  75. .catch((error) => {
  76. throw error;
  77. });
  78. }