ts + axios + useRequest (ahooks)—— 实现请求封装

现在越来越多的项目开始ts化,我们今天就一块学习一下,关于ts的请求封装。

首先要安装两个依赖:

npm i axios -S

npm i ahooks -S

引入:

javascript 复制代码
import { useRequest } from 'ahooks';
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';

定义一个泛型接口,用于指定请求参数和响应数据的类型

javascript 复制代码
interface RequestParams<T> {
  url: string;
  method: string;
  data?: T;
}

// 定义一个范型函数,用于发送 GET 请求
function get<T>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
  return axios.get<T>(url, config);
}

// 定义一个范型函数,用于发送 POST 请求
function post<T>(params: RequestParams<T>, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
  return axios.post<T>(params.url, params.data, config);
}

使用ahooks的useRequest:

javascript 复制代码
 // 使用 useRequest hooks 发送 GET 请求
  const { data, loading, error } = useRequest<{ name: string }>('https://api.example.com/data', {
    requestMethod: () => get('https://api.example.com/data'),
  });

直接使用get、post:

javascript 复制代码
// 调用 GET 方法
get<{ name: string }>('https://api.example.com/data')
  .then(response => {
    console.log(response.data.name);
  })
  .catch(error => {
    console.error(error);
  });

// 调用 POST 方法
const postData = { name: 'John' };
const postParams = { url: 'https://api.example.com/data', method: 'post', data: postData };
post<{ status: string }>(postParams)
  .then(response => {
    console.log(response.data.status);
  })
  .catch(error => {
    console.error(error);
  });
相关推荐
子兮曰3 小时前
OpenClaw入门:从零开始搭建你的私有化AI助手
前端·架构·github
吴仰晖3 小时前
使用github copliot chat的源码学习之Chromium Compositor
前端
1024小神3 小时前
github发布pages的几种状态记录
前端
不像程序员的程序媛6 小时前
Nginx日志切分
服务器·前端·nginx
北原_春希6 小时前
如何在Vue3项目中引入并使用Echarts图表
前端·javascript·echarts
尽意啊6 小时前
echarts树图动态添加子节点
前端·javascript·echarts
吃面必吃蒜6 小时前
echarts 极坐标柱状图 如何定义柱子颜色
前端·javascript·echarts
O_oStayPositive6 小时前
Vue3使用ECharts
前端·javascript·echarts
竹秋…6 小时前
echarts自定义tooltip中的内容
前端·javascript·echarts
宝贝露.6 小时前
Axure引入Echarts图无法正常显示问题
前端·javascript·echarts