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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值