vue3使用ts封装axios

以下是使用 TypeScript 封装 Axios 的示例代码:

复制代码
//axios.ts

import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios';

// 自定义 API 响应类型
interface ApiResponse<T> {
  code: number;
  message: string;
  data: T;
}

// 自定义错误类型
interface ApiError {
  code: number;
  message: string;
}

// 创建自定义的 Axios 实例
const api: AxiosInstance = axios.create({
  baseURL: 'https://api.example.com', // 设置基础 URL
  timeout: 5000, // 请求超时时间
});

// 请求拦截器
api.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // 在发送请求之前做一些处理,例如添加请求头等
    // config.headers['Authorization'] = 'Bearer token';
    return config;
  },
  (error: AxiosError) => {
    // 处理请求错误
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response: AxiosResponse<ApiResponse<any>>) => {
    // 在这里对响应进行处理,例如处理错误状态码等
    const { code, message, data } = response.data;
    if (code === 0) {
      // 请求成功
      return data;
    } else {
      // 请求失败,抛出自定义的错误
      const error: ApiError = {
        code,
        message,
      };
      return Promise.reject(error);
    }
  },
  (error: AxiosError) => {
    // 处理响应错误
    return Promise.reject(error);
  }
);

// 封装 GET 请求
export function get<T>(url: string, params?: any): Promise<T> {
  return api.get<ApiResponse<T>>(url, { params })
    .then((response: ApiResponse<T>) => response.data)
    .catch((error: ApiError) => {
      throw new Error(error.message);
    });
}

// 封装 POST 请求
export function post<T>(url: string, data?: any): Promise<T> {
  return api.post<ApiResponse<T>>(url, data)
    .then((response: ApiResponse<T>) => response.data)
    .catch((error: ApiError) => {
      throw new Error(error.message);
    });
}

// 使用示例
get<User[]>('/users')
  .then((users: User[]) => {
    // 处理获取到的用户数据
  })
  .catch((error: Error) => {
    // 处理错误
  });

post<User>('/users', { name: 'John', age: 30 })
  .then((user: User) => {
    // 处理创建用户成功的响应
  })
  .catch((error: Error) => {
    // 处理错误
  });

在示例代码中,我们使用 TypeScript 创建了一个自定义的 Axios 实例 `api`,并在其中配置了请求拦截器和响应拦截器。我们还封装了 `get` 和 `post` 方法来发起 GET 和 POST 请求,并处理了响应数据和错误。

请注意,示例中的 `ApiResponse` 类型和 `ApiError` 类型是根据具体的 API 响应格式进行定义的,您可以根据自己的实际情况进行调整。此外,您还可以根据需要添加其他的封装方法,例如 PUT、DELETE 等。

希望这个示例能帮助您封装 Axios 并进行 TypeScript 开发。如有任何问题,请随时提问。

相关推荐
A小辣椒11 小时前
TShark:Wireshark CLI 功能
linux
A小辣椒15 小时前
TShark:基础知识
linux
AlfredZhao17 小时前
OCI 明明分配了 200G 系统盘,为什么 df 只看到 30G?
linux·oci
AlfredZhao1 天前
vi 删除指定范围的行,不用再反复按 dd
linux·vi
用户9718356334662 天前
银河麒麟 KY10 申威(SW64) 安装 nginx-1.16.1-2.p01.ky10.sw_64.rpm 详细步骤
linux
猪脚踏浪2 天前
linux 拷贝文件或目录到指定的位置
linux
大树882 天前
金刚石散热越强,管路越先见顶
大数据·运维·服务器·人工智能·ai
摇滚侠2 天前
Linux CentOS7 rpm 安装 MySQL 5.7
linux·运维·mysql
霸道流氓气质2 天前
领域驱动设计(DDD)在 Spring Boot 微服务中的实践指南
运维·spring boot·微服务
bush42 天前
嵌入式linux学习记录十四、术语
linux·嵌入式