ts如何封装axios

发布时间:2023-03-13 11:15:34 作者:iii
来源:亿速云 阅读:526

TS如何封装Axios

在现代前端开发中,网络请求是不可避免的一部分。Axios 是一个基于 Promise 的 HTTP 客户端,广泛应用于浏览器和 Node.js 环境中。TypeScript 是 JavaScript 的超集,提供了静态类型检查和更强大的工具支持。结合 TypeScript 和 Axios,我们可以构建出更加健壮和可维护的网络请求模块。

本文将详细介绍如何在 TypeScript 中封装 Axios,包括基础封装、请求拦截、响应拦截、错误处理、类型定义、泛型支持等内容。通过本文的学习,你将能够掌握如何在 TypeScript 项目中高效地使用 Axios。

目录

  1. Axios 基础
  2. TypeScript 基础
  3. 封装 Axios 的必要性
  4. 基础封装
  5. 请求拦截
  6. 响应拦截
  7. 错误处理
  8. 类型定义
  9. 泛型支持
  10. 高级封装
  11. 总结

Axios 基础

Axios 是一个基于 Promise 的 HTTP 客户端,可以在浏览器和 Node.js 中使用。它具有以下特点:

安装

npm install axios

基本使用

import axios from 'axios';

axios.get('https://api.example.com/data')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

TypeScript 基础

TypeScript 是 JavaScript 的超集,提供了静态类型检查和更强大的工具支持。通过 TypeScript,我们可以在开发阶段发现潜在的错误,提高代码的可维护性和可读性。

安装

npm install typescript --save-dev

基本使用

function greet(name: string): string {
  return `Hello, ${name}!`;
}

console.log(greet('World'));

封装 Axios 的必要性

在实际项目中,直接使用 Axios 可能会导致代码重复、难以维护。通过封装 Axios,我们可以实现以下目标:

基础封装

首先,我们创建一个 axiosInstance,并对其进行基础封装。

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

const axiosInstance: AxiosInstance = axios.create({
  baseURL: 'https://api.example.com',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

export default axiosInstance;

使用封装后的 Axios

import axiosInstance from './axiosInstance';

axiosInstance.get('/data')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

请求拦截

请求拦截器可以在请求发送之前对请求进行处理,例如添加认证信息、设置请求头等。

axiosInstance.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

响应拦截

响应拦截器可以在响应到达之前对响应进行处理,例如统一处理错误、转换数据格式等。

axiosInstance.interceptors.response.use(
  (response: AxiosResponse) => {
    if (response.status === 200) {
      return response.data;
    } else {
      return Promise.reject(response);
    }
  },
  (error) => {
    return Promise.reject(error);
  }
);

错误处理

在实际项目中,错误处理是非常重要的一部分。我们可以通过拦截器统一处理错误。

axiosInstance.interceptors.response.use(
  (response: AxiosResponse) => {
    return response;
  },
  (error) => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 处理未授权错误
          break;
        case 404:
          // 处理未找到资源错误
          break;
        default:
          // 处理其他错误
          break;
      }
    }
    return Promise.reject(error);
  }
);

类型定义

TypeScript 的强大之处在于其类型系统。我们可以为 Axios 请求和响应定义类型,以提高代码的可读性和可维护性。

定义请求和响应类型

interface User {
  id: number;
  name: string;
  email: string;
}

interface ApiResponse<T> {
  data: T;
  status: number;
  message: string;
}

使用类型定义

axiosInstance.get<ApiResponse<User>>('/user/1')
  .then(response => {
    const user: User = response.data.data;
    console.log(user);
  })
  .catch(error => {
    console.error(error);
  });

泛型支持

通过泛型,我们可以进一步简化代码,并提高代码的复用性。

定义泛型请求函数

function get<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
  return axiosInstance.get<T>(url, config).then(response => response.data);
}

使用泛型请求函数

get<ApiResponse<User>>('/user/1')
  .then(response => {
    const user: User = response.data;
    console.log(user);
  })
  .catch(error => {
    console.error(error);
  });

高级封装

在实际项目中,我们可能需要更复杂的封装,例如支持多种请求方法、统一处理分页、缓存等。

支持多种请求方法

function request<T>(config: AxiosRequestConfig): Promise<T> {
  return axiosInstance.request<T>(config).then(response => response.data);
}

function get<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
  return request<T>({ ...config, method: 'GET', url });
}

function post<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
  return request<T>({ ...config, method: 'POST', url, data });
}

function put<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
  return request<T>({ ...config, method: 'PUT', url, data });
}

function delete<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
  return request<T>({ ...config, method: 'DELETE', url });
}

统一处理分页

interface PaginationParams {
  page: number;
  pageSize: number;
}

interface PaginationResponse<T> {
  data: T[];
  total: number;
}

function getWithPagination<T>(url: string, params: PaginationParams, config?: AxiosRequestConfig): Promise<PaginationResponse<T>> {
  return get<PaginationResponse<T>>(url, { ...config, params });
}

缓存支持

const cache = new Map<string, any>();

function getWithCache<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
  if (cache.has(url)) {
    return Promise.resolve(cache.get(url));
  }
  return get<T>(url, config).then(data => {
    cache.set(url, data);
    return data;
  });
}

总结

通过本文的学习,我们了解了如何在 TypeScript 中封装 Axios。从基础封装到高级封装,我们逐步构建了一个健壮、可维护的网络请求模块。通过类型定义和泛型支持,我们进一步提高了代码的可读性和可复用性。在实际项目中,合理封装 Axios 可以大大提高开发效率和代码质量。

希望本文对你有所帮助,祝你在 TypeScript 和 Axios 的世界中探索出更多精彩的内容!

推荐阅读:
  1. vue axios 简单封装以及思考
  2. 如何在vue中封装axios

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

ts axios

上一篇:C++预处理连接方法怎么使用

下一篇:python如何计算圆的面积

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》