react+ ts vite搭建及二次封装请求的过程解析
作者:——a
这篇文章主要介绍了react+ ts vite搭建及二次封装请求,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
1.搭建项目
npm create vite
2.下载axios
npm install axios
打开项目创建基本项目结构
3.创建http文件夹下index.ts
引入axios
import axios, { AxiosResponse, AxiosInstance, InternalAxiosRequestConfig, } from "axios";
重新创建axios
const instance: AxiosInstance = axios.create({ baseURL: // vite 环境变量判断 import.meta.env.MODE === "development" ? "/api" : import.meta.env.VITE_APP_BASE_URL, timeout: 10000, });
创建拦截器
instance.interceptors.request.use((config: InternalAxiosRequestConfig) => { //进行特殊请求操作 return config; }); instance.interceptors.response.use((response: AxiosResponse) => { return response.data; });
封装请求方法
export function get<T>( url: string, params?: CustomObject, config?: CustomObject ): Promise<ResultData> { return instance.get(url, { params, ...config }); } export function post<T>( url: string, params?: CustomObject, config?: CustomObject ): Promise<ResultData> { return instance.post(url, params, config); } export function put<T>( url: string, params?: CustomObject, config?: CustomObject ): Promise<ResultData> { return instance.put(url, params, config); }
导出
export default instance;
完整代码
// http/index.ts import axios, { AxiosResponse, AxiosInstance, InternalAxiosRequestConfig, } from "axios"; const instance: AxiosInstance = axios.create({ baseURL: import.meta.env.MODE === "development" ? "/api" : import.meta.env.VITE_APP_BASE_URL, timeout: 10000, }); instance.interceptors.request.use((config: InternalAxiosRequestConfig) => { //进行特殊请求操作 return config; }); instance.interceptors.response.use((response: AxiosResponse) => { return response.data; }); export function get<T>( url: string, params?: CustomObject, config?: CustomObject ): Promise<ResultData> { return instance.get(url, { params, ...config }); } export function post<T>( url: string, params?: CustomObject, config?: CustomObject ): Promise<ResultData> { return instance.post(url, params, config); } export function put<T>( url: string, params?: CustomObject, config?: CustomObject ): Promise<ResultData> { return instance.put(url, params, config); } export default instance;
使用
// api.ts import { get, post } from "../http/index"; // 文章列表 export const blogList = (data: CustomObject): Promise<ResultData> => get("/api/posts", data);
到此这篇关于react+ ts vite搭建及二次封装请求的文章就介绍到这了,更多相关react二次封装请求内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!