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

相关推荐
人工智能训练4 小时前
OpenEnler等Linux系统中安装git工具的方法
linux·运维·服务器·git·vscode·python·ubuntu
QT 小鲜肉5 小时前
【Linux命令大全】001.文件管理之which命令(实操篇)
linux·运维·服务器·前端·chrome·笔记
oMcLin5 小时前
Ubuntu 22.04 无法连接外部网络的故障排查与解决(解决 DNS 配置问题)
linux·网络·ubuntu
还不秃顶的计科生6 小时前
LeetCode 热题 100第二题:字母易位词分组python版本
linux·python·leetcode
咯哦哦哦哦6 小时前
WSL + ubantu22.04 + 远程桌面闪退+黑屏闪退解决
linux·开发语言
fantasy5_56 小时前
Linux 动态进度条实战:从零掌握开发工具与核心原理
linux·运维·服务器
weixin_462446236 小时前
exo + tinygrad:Linux 节点设备能力自动探测(NVIDIA / AMD / CPU 安全兜底)
linux·运维·python·安全
..过云雨6 小时前
17-2.【Linux系统编程】线程同步详解 - 条件变量的理解及应用
linux·c++·人工智能·后端
莫逸风6 小时前
【局域网服务方案】:无需找运营商,低成本拥有高性能服务器
运维·服务器
oMcLin7 小时前
CentOS 7 频繁出现 “Connection Refused” 错误的原因分析与解决
linux·运维·centos