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

相关推荐
root666/9 分钟前
【后端开发-nginx】proxy_pass和proxy_redirect参数作用
运维·nginx
用户61354114601610 分钟前
xampplinux_v174beta11在 Linux 下的安装与配置步骤
linux
Byron Loong16 分钟前
【系统】Mac系统和Linux 指令对比
linux·macos·策略模式
markvivv41 分钟前
在 Kylin Linux Advanced Server for Kunpeng V10 上构建 VSCode 1.106
linux·vscode·kylin
2501_940414081 小时前
搞了一次平台工程,我把本地的 Docker Desktop 彻底卸了
运维·docker·容器
看见繁华1 小时前
Linux 交叉编译实践笔记
linux·运维·笔记
咕噜企业分发小米1 小时前
直播云服务器安全防护有哪些最新的技术趋势?
运维·服务器·安全
tianyuanwo1 小时前
深入解析CentOS 8网络配置:NetworkManager DNS管理机制与网卡类型深度剖析
linux·网络·centos
tianyuanwo1 小时前
深入解析CentOS 8中NetworkManager重启后DNS配置被覆盖的机制与解决方案
linux·运维·centos·dns
Dragon~Snow1 小时前
Linux-centOS Stream 9 系统 mysql-8.4.7 RPM版本
linux·mysql·centos