美文网首页
TypeScript学习笔记之axios简单封装

TypeScript学习笔记之axios简单封装

作者: 冬季穿短裤 | 来源:发表于2022-02-22 20:42 被阅读0次

TypeScript对比JavaScript最大的区别就是TypeScript是强类型的。这种强类型相比弱类型,可以在编译期间发现并纠正错误,降低了试错的成本(智能提示)也提升了代码的规范性。

axios封装

//http.ts

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

const config = {
    baseURL: /*读取配置文件*/process.env.VUE_APP_BASE_API_URL,
    timeout: 10 * 1000,
    withCredentials: true
};

const requestInterceptor = (config: AxiosRequestConfig): AxiosRequestConfig => {
    //请求拦截器,自定义
    return config;
};

const http: AxiosInstance = axios.create(config);
http.interceptors.request.use(requestInterceptor, error => Promise.reject(error))
http.interceptors.response.use(response => Promise.resolve(response), error => Promise.reject(error))

export function httpRequest<T>(config: AxiosRequestConfig): Promise<T> {
    const promise = http.request<T, AxiosResponse<T>>(config);
    return convertAxiosResponse(promise);
}

export function httpGet<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    const promise = http.get<T, AxiosResponse<T>>(url, config);
    return convertAxiosResponse(promise);
}

export function httpDelete<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    const promise = http.delete<T, AxiosResponse<T>>(url, config);
    return convertAxiosResponse(promise);
}

export function httpHead<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    const promise = http.head<T, AxiosResponse<T>>(url, config);
    return convertAxiosResponse(promise);
}

export function httpOptions<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    const promise = http.options<T, AxiosResponse<T>>(url, config);
    return convertAxiosResponse(promise);
}

export function httpPost<T, D>(url: string, data?: D, config?: AxiosRequestConfig): Promise<T> {
    const promise = http.post<T, AxiosResponse<T>, D>(url, data, config)
    return convertAxiosResponse(promise);
}

export function httpPut<T, D>(url: string, data?: D, config?: AxiosRequestConfig): Promise<T> {
    const promise = http.put<T, AxiosResponse<T>, D>(url, data, config);
    return convertAxiosResponse(promise);
}

export function httpPatch<T, D>(url: string, data?: D, config?: AxiosRequestConfig): Promise<T> {
    const promise = http.patch<T, AxiosResponse<T>, D>(url, data, config);
    return convertAxiosResponse(promise);
}

/**
 * @param axiosPromise AxiosResponse<T>
 */
function convertAxiosResponse<T>(axiosPromise: Promise<AxiosResponse<T>>): Promise<T> {
    return new Promise(function (resolve, reject) {
        axiosPromise.then(response => {
            resolve(response.data)
        }).then(err => {
            reject(err)
        });
    });
}

接口返回实体

因为是强类型的,支持泛型,所有我们可以把数据封装成一个实体类(或接口),这样参数就一目了然,类似Java中JavaBean的使用。
如果接口返回有统一的格式,如:

{
    "code": 200,
    "msg": "success",
    "data": any
}

那么就可以定义一个Base类(或接口),data以泛型参数传入。

//api-bean.ts

export interface ApiResponse<T = any> {
    code: number;
    msg: string;
    data: T;
}

export interface UserInfoBean {
    createdAt: string;
    id: number;
    userId: string;
    userType: string;
    username: string;
}

/**
 * 登录使用
 */
export interface UserLoginBean {
    userId: string;
    password: string;
    userType: string;
}

使用示例


import {httpGet, httpPost} from "@/util/http"
import {ApiResponse, UserInfoBean, UserLoginBean} from "@/bean/api-bean";

httpGet<ApiResponse<UserInfoBean[]>>("/srs_rtc/user/getAllUserInfo")
    .then((response) => {
      console.log("httpGet:", response)
    })
const login: UserLoginBean = {
  userId: "test",
  password: "1",
  userType: "0"
}
httpPost<ApiResponse<UserInfoBean>, UserLoginBean>("/srs_rtc/user/userLogin", login).then(response => {
  console.log("httpPost:", response)
}).then(error => {
  //
})

使用的时候就有智能提示了,相比JavaScript是不是爽很多?


示例

本人刚刚入手TypeScript,如有使用不当之处,欢迎指正。

相关文章

  • TypeScript学习笔记之axios简单封装

    TypeScript对比JavaScript最大的区别就是TypeScript是强类型的。这种强类型相比弱类型,可...

  • 封装Axios与制定Service层

    封装Axios 在项目中我们通常使用的是axios,由于我们的项目采用的是typescript,以下记录怎么在ts...

  • 在VUE中科学使用axios

    在项目中安装axios 封装axios 新建api/index.js文件,对axios进行简单的封装,方便使用。真...

  • axios封装(简单封装)

    菜鸟一枚,如有错误,欢迎指正。 安装 npm install axios; 1.引入 import axios f...

  • axios请求封装

    axios封装 简单设置本地mock数据

  • Typescript

    TypeScript(TS)部分 TypeScript学习笔记

  • axios简单封装

    Vue 折腾记 - 给axios做个挺靠谱的封装(报错,鉴权,跳转,拦截,提示) 借鉴引用 本篇文章给大家带来的内...

  • axios简单封装

    本想着直接用,不要封装,也很方便。后来发现还是要简单封装一下,省掉一些重复的验证。重点在resolve和rejec...

  • axios简单封装

    1、安装axios npm install axios --save 或 yarn add axios ...

  • axios简单封装

网友评论

      本文标题:TypeScript学习笔记之axios简单封装

      本文链接:https://www.haomeiwen.com/subject/vzfnlrtx.html