吉安手机网站建设,网站的网页设计毕业设计,网站建设的本质,最新的新闻 今天现在越来越多的项目开始ts化#xff0c;我们今天就一块学习一下#xff0c;关于ts的请求封装。
首先要安装两个依赖#xff1a;
npm i axios -S
npm i ahooks -S
引入#xff1a;
import { useRequest } from ahooks;
import axios, { AxiosRequestConfig, AxiosRespo…现在越来越多的项目开始ts化我们今天就一块学习一下关于ts的请求封装。
首先要安装两个依赖
npm i axios -S
npm i ahooks -S
引入
import { useRequest } from ahooks;
import axios, { AxiosRequestConfig, AxiosResponse } from axios;
定义一个泛型接口用于指定请求参数和响应数据的类型
interface RequestParamsT {url: string;method: string;data?: T;
}// 定义一个范型函数用于发送 GET 请求
function getT(url: string, config?: AxiosRequestConfig): PromiseAxiosResponseT {return axios.getT(url, config);
}// 定义一个范型函数用于发送 POST 请求
function postT(params: RequestParamsT, config?: AxiosRequestConfig): PromiseAxiosResponseT {return axios.postT(params.url, params.data, config);
}
使用ahooks的useRequest // 使用 useRequest hooks 发送 GET 请求const { data, loading, error } useRequest{ name: string }(https://api.example.com/data, {requestMethod: () get(https://api.example.com/data),});
直接使用get、post
// 调用 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);});