当前位置: 首页 > news >正文

[前端] axios网络请求二次封装

一、场景描述

为什么要对axios网络请求进行二次封装?
解决代码的复用,提高可维护性。 —这个有两个方案:一个是二次封装一个是实例化。(设置一些公共的参数,然后进行请求)
为什么可以解决代码的复用:
这是最简单格式的代码,需要定义url和请求方式。

axios({method: "get",url: "http://codercba.com:9002/banner",
}).then(function (response) {console.log(response);
}).catch(function (error) {console.log(error);
});

封装之后的请求方式,减少了点代码

    hyRequest.get({ url: "/banner" }).then((res) => {console.log(res);setImg(res.banners);console.log(img);});

Axios实例化的输出

const instance = axios.create({baseURL: "http://codercba.com:9002",
});instance.get("banner").then((response) => {console.log("实例化请求输出");console.log(response);
});

二、二次封装的代码实现

type.ts //定义一些类型

import type {InternalAxiosRequestConfig,AxiosRequestConfig,AxiosResponse,AxiosRequestHeaders,
} from "axios";export interface HYInterceptors<T = AxiosResponse> {   //定义拦截器类型requestSuccessFn?: (config: InternalAxiosRequestConfig) => InternalAxiosRequestConfig;requestFailureFn?: (err: any) => any;responseSuccessFn?: (res: T) => T;responseFailureFn?: (err: any) => any;
}export interface HYRequestConfig<T = AxiosResponse> extends AxiosRequestConfig {      //定义请求体的配置   interceptors?: HYInterceptors<T>;headers?: AxiosRequestHeaders;
}

request.ts //封装axios

import axios, { InternalAxiosRequestConfig } from "axios";
import type { AxiosInstance } from "axios";
import type { HYRequestConfig } from "./type";class HYRequest {instance: AxiosInstance;     //实例constructor(config: HYRequestConfig) {   this.instance = axios.create(config);     //实例化axiosthis.instance.interceptors.response.use((config) => {return config;},(err) => {return err;});this.instance.interceptors.response.use((res) => {return res.data;},(err) => {return err;});this.instance.interceptors.request.use(config.interceptors?.requestSuccessFn,config.interceptors?.requestFailureFn);this.instance.interceptors.response.use(config.interceptors?.responseSuccessFn,config.interceptors?.responseFailureFn);}request<T = any>(config: HYRequestConfig<T>) {if (config.interceptors?.requestSuccessFn) {config = config.interceptors.requestSuccessFn(config as InternalAxiosRequestConfig);}return new Promise<T>((resolve, reject) => {this.instance      //实例请求 .request<any, T>(config).then((res) => {if (config.interceptors?.responseSuccessFn) {res = config.interceptors.responseSuccessFn(res);}resolve(res);}).catch((err) => {reject(err);});});}get<T = any>(config: HYRequestConfig<T>) {return this.request({ ...config, method: "GET" });}post<T = any>(config: HYRequestConfig<T>) {return this.request({ ...config, method: "POST" });}delete<T = any>(config: HYRequestConfig<T>) {return this.request({ ...config, method: "DELETE" });}patch<T = any>(config: HYRequestConfig<T>) {return this.request({ ...config, method: "PATCH" });}
}export default HYRequest;

index.ts //实例化

import { BASE_URL, TIME_OUT } from "./config";
import HYRequest from "./request";const hyRequest = new HYRequest({baseURL: BASE_URL,timeout: TIME_OUT,interceptors: {requestSuccessFn: (config) => {return config;},},
});export default hyRequest;

可以看到其实封装也是先实例化之后再进行封装。为什么要这么做,实例化的东西不太好维护。包括对拦截器的更新。
在这里插入图片描述
三、上述内容整体概述
在这里插入图片描述

四、axios相关内容
在这里插入图片描述
在这里插入图片描述

http://www.lryc.cn/news/535787.html

相关文章:

  • 本地部署DeepSeek Nodejs版
  • 【PL/SQL】常用操作复习20250212
  • vue3-02基础认识vue3中main.js入口文件,app.vue(不存在唯一根节点),扩展程序vue-devtools安装
  • 如何下载Qt和运行第一个程序。
  • 【MySQL例题】我在广州学Mysql 系列——有关数据备份与还原的示例
  • 硬件学习笔记--40 电磁兼容试验-4 快速瞬变脉冲群试验介绍
  • 国密算法SM1、SM2、SM3和SM4 具体的使用和区别
  • 在Ubuntu中安装Docker并配置国内镜像
  • 【大模型】阿里云百炼平台对接DeepSeek-R1大模型使用详解
  • DeepSeek本地部署详细指南
  • 厘米和磅的转换关系
  • Unity-Mirror网络框架-从入门到精通之LagCompensation示例
  • DeepSeek+3D视觉机器人应用场景、前景和简单设计思路
  • STM32+Proteus+DS18B20数码管仿真实验
  • Java自动生成api文档
  • PHP的JIT编译器
  • Golang学习历程【第七篇 闭包type defer panic recover了解time包】
  • oracle表分区--范围分区
  • 使用亚马逊针对 PyTorch 和 MinIO 的 S3 连接器进行模型检查点处理
  • Ubuntu 下 nginx-1.24.0 源码分析 - ngx_monotonic_time函数
  • 业务开发 | 基础知识 | Maven 快速入门
  • 基于 Python(Flask)、JavaScript、HTML 和 CSS 实现前后端交互的详细开发过程
  • STM32 RCC功能说明 复位和时钟控制RCC
  • Windows可以永久暂停更新了
  • 高级 Python Web 开发:基于 FastAPI 构建高效实时聊天系统与并发控制
  • 深入理解Java虚拟机(JVM)
  • 笔试面试——逻辑题
  • 【深度学习入门实战】基于Keras的手写数字识别实战(附完整可视化分析)
  • 软考高级《系统架构设计师》知识点(一)
  • 用大模型学大模型01-制定学习计划