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 开发。如有任何问题,请随时提问。

相关推荐
云途行者1 分钟前
使用 docker 安装 openldap
运维·docker·容器
群联云防护小杜8 分钟前
深度隐匿源IP:高防+群联AI云防护防绕过实战
运维·服务器·前端·网络·人工智能·网络协议·tcp/ip
YuTaoShao19 分钟前
【LeetCode 热题 100】994. 腐烂的橘子——BFS
java·linux·算法·leetcode·宽度优先
退役小学生呀22 分钟前
十五、K8s可观测能力:日志收集
linux·云原生·容器·kubernetes·k8s
van叶~23 分钟前
Linux探秘坊-------15.线程概念与控制
linux·运维·服务器
Andy杨2 小时前
20250718-1-Kubernetes 应用程序生命周期管理-应用部署、升级、弹性_笔记
linux·docker·容器
写写闲篇儿6 小时前
Python+MongoDB高效开发组合
linux·python·mongodb
一个龙的传说7 小时前
linux 常用命令
linux·服务器·zookeeper
别致的影分身8 小时前
Docker 镜像原理
运维·docker·容器