项目中使用Typescript封装axios

yizhihongxing

一、什么是 Typescript

Typescript 是JavaScript 的一个超集,它不仅支持JavaScript的语法,还增加了许多新的特性。最重要的是,Typescript 具有类型检查的能力,能在编译时即可检查出代码中的类型错误,提高了代码的可靠性和可维护性。

二、什么是 Axios

Axios 是一个基于Promise 的HTTP 客户端,用于浏览器和 Node.js。它使用封装的 XMLHttpRequests 对象或者浏览器原生的 fetch 进行网络请求,并且提供额外的一些辅助功能。它具有可立即使用的极简主义API,以及在高级用法下完全的定制能力。

三、使用 Typescript 封装 Axios

在项目中使用 Typescript 封装 Axios,主要步骤如下:

  1. 安装依赖:通过 npm 安装 axios、@types/axios 和 typescript 依赖包:
npm install axios @types/axios typescript
  1. 创建封装的 axios 类和接口文件:
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';

interface IAxios {
  request<T = any>(config: AxiosRequestConfig): Promise<T>;
  get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T>;
  post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T>;
  put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T>;
  delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<T>;
}

class Axios {
  private axiosInstance: AxiosInstance;
  constructor() {
    this.axiosInstance = axios.create({ timeout: 10000 });
    this.init();
  }

  // 初始化拦截器
  private init() {
    // 定义请求拦截器
    this.axiosInstance.interceptors.request.use(
      (config: AxiosRequestConfig) => {
        // 可以根据业务需求修改请求头
        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );

    // 定义响应拦截器
    this.axiosInstance.interceptors.response.use(
      (response: AxiosResponse) => {
        // 根据后端返回的状态码进行处理,如登录过期、请求失败等
        return response.data;
      },
      (error) => {
        return Promise.reject(error);
      }
    );
  }

  // 封装 axios 请求方法
  public request<T = any>(config: AxiosRequestConfig): Promise<T> {
    return this.axiosInstance
      .request<T>(config)
      .then((res) => res)
      .catch((error) => Promise.reject(error));
  }

  public get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return this.axiosInstance
      .get<T>(url, config)
      .then((res) => res)
      .catch((error) => Promise.reject(error));
  }

  public post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return this.axiosInstance
      .post<T>(url, data, config)
      .then((res) => res)
      .catch((error) => Promise.reject(error));
  }

  public put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return this.axiosInstance
      .put<T>(url, data, config)
      .then((res) => res)
      .catch((error) => Promise.reject(error));
  }

  public delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return this.axiosInstance
      .delete<T>(url, config)
      .then((res) => res)
      .catch((error) => Promise.reject(error));
  }
}

export default Axios;
export { IAxios };

以上代码中,首先定义了封装的 axios 类和接口,通过 typescript 的泛型支持来实现返回数据类型的约束。在定义完类之后,我们需要在类里面通过 axios.create 方法来创建 axios 实例,这样我们就可以通过封装好的方法来发送请求了。

其中,init 方法是用于安装拦截器的。

  1. 测试接口

这里提供一个简单的示例来测试接口:

import Axios from './Axios';

interface IData {
  name: string;
  age: number;
}

const axios = new Axios();

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

axios
  .post<IData>('http://example.com/api/data', { name: 'Tom', age: 18 })
  .then((response) => {
    console.log(response);
  })
  .catch((error) => {
    console.log(error);
  });

这里我们首先导入封装好的 axios 类,并且定义数据接口。然后创建 axios 实例,调用 get 和 post 方法向服务器发送请求,并输出结果。我们可以根据服务器返回的数据类型进行类型约束。

以上就是使用 Typescript 封装 axios 并测试接口的完整攻略。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:项目中使用Typescript封装axios - Python技术站

(0)
上一篇 2023年6月25日
下一篇 2023年6月25日

相关文章

  • html5 video标签屏蔽右键视频另存为的js代码

    要实现html5 video标签屏蔽右键视频另存为,我们可以使用Javascript代码来解决。具体的实现过程如下: 1. 创建一个video标签 首先,我们需要在HTML中创建一个video标签,并指定要加载的视频文件路径。 <video id="myVideo" controls preload="metadata&q…

    other 2023年6月27日
    00
  • C语言中计算字符串长度与分割字符串的方法

    计算字符串长度 在C语言中,可以通过strlen()函数计算字符串的长度。strlen()函数是字符串操作函数之一,定义在头文件<string.h>中。 使用示例: #include <stdio.h> #include <string.h> int main() { char str[] = "hello, w…

    other 2023年6月20日
    00
  • Spring中属性注入的几种方式以及复杂属性的注入详解

    Spring中属性注入的几种方式以及复杂属性的注入详解 在Spring框架中,属性注入是一种常见的依赖注入方式,它允许我们将属性值注入到对象中,以实现对象之间的解耦和灵活性。Spring提供了多种属性注入的方式,包括构造函数注入、Setter方法注入和注解注入。下面将详细介绍这几种方式,并提供示例说明。 1. 构造函数注入 构造函数注入是通过对象的构造函数来…

    other 2023年8月6日
    00
  • 如何使用WPS表格转换为歌词句首字母改大写

    如何使用WPS表格转换为歌词句首字母改大写 在WPS表格中,你可以使用公式和函数来将歌词句的首字母改为大写。下面是详细的攻略,包含两个示例说明。 步骤一:准备数据 首先,你需要在WPS表格中准备好你的歌词数据。确保歌词句位于一个单独的列中,例如\”A\”列。 示例数据如下: A hello world openai markdown 步骤二:使用公式转换首字…

    other 2023年8月19日
    00
  • 详解vue 组件注册

    绝大多数 Vue 项目中,你都需要定义自己的组件。在文档中,Vue 组件被描述为可复用的 Vue 实例,因为它们实际上就是 Vue 实例,接受相同的选项对象 (除了一些根实例特有的选项)。 组件系统是 Vue 的核心特性之一,它使构建大型应用程序变得更加容易。 全局注册组件 在 Vue 应用程序中注册一个全局组件非常简单,只需要调用 Vue.componen…

    other 2023年6月27日
    00
  • Tomcat实现热部署

    以下是Tomcat实现热部署的完整攻略: 配置Tomcat的context.xml文件: 打开Tomcat安装目录下的conf/context.xml文件。 在<Context>标签内添加reloadable=\”true\”属性,如下所示: xml <Context reloadable=\”true\”> 保存并关闭文件。 配置T…

    other 2023年10月14日
    00
  • PHP正则的Unknown Modifier错误解决方法

    当你在使用PHP正则表达式时,有时候会遇到 “Unknown Modifier” 错误。这个错误通常是由于在正则表达式模式字符串中使用了一个未知修饰符造成的。本文将会对这个问题进行详细的阐述,并提供两个示例来解决该问题。 什么是正则表达式的修饰符 正则表达式的模式字符串可以包含修饰符,这些修饰符用于调整模式的匹配行为。例如,在PCRE (Perl Compa…

    other 2023年6月27日
    00
  • 谷歌Chrome 56正式版第二个维护版发布:安全修复

    谷歌Chrome 56正式版第二个维护版发布:安全修复攻略 简介 谷歌Chrome是一款流行的网络浏览器,它经常发布维护版来修复安全漏洞和改进用户体验。本攻略将详细介绍谷歌Chrome 56正式版第二个维护版的发布过程,并提供两个示例说明。 步骤1: 下载维护版 首先,你需要下载谷歌Chrome 56正式版第二个维护版的安装程序。你可以通过以下步骤完成下载:…

    other 2023年8月3日
    00
合作推广
合作推广
分享本页
返回顶部