Vue3框架搭建2:axios+typescript封装

仓库地址:https://github.com/buguniao5213/LuArch(分支代码未上传,完整一系列后传一波,中途有需求可以再传)

1、安装axios

复制代码
npm install axios

2、创建文件

先创建一个文件夹:

复制代码
├── src/
│   ├── api/        
│   │   ├── index.ts/   #编写axios封装代码    
│   │   └── example.ts/ #定义向后端服务器发送请求的模块`

├── publix/
│   ├── json/        
│   │   └── example.json/   #模拟get接口获取到的数据`

3、导入申明

导入axios库和相关类型

复制代码
import axios, { type AxiosInstance, type AxiosRequestConfig } from 'axios';

4、基础url定义

这个后面放到vite的缓建变量配置中(.env)

复制代码
const BASE_URL = '/'

5、定义request类

要素如下:

复制代码
export class Request {
    private instance: AxiosInstance;
    private baseConfig: AxiosRequestConfig = { baseURL: BASE_URL, timeout: 60000 };
    public constructor() {
        //...    
    }
    public request() {
        //...    
    }
    public get() {
        //...    
    }
    
    //...
    //...
}

a)、private instance:私有属性instance:Axios实例

b)、private baseConfig:基本配置,包括基础URL和超时时间

c)、public constructor:构造函数

创建Axios实例,合并基本配置和传入配置

设置请求拦截器:可以添加token等认证信息

设置响应拦截器:处理相应数据,根据状态码决定返回数据或报错误信息

d)、请求方法设置:

request:通用请求方法。

get:GET请求方法。

post: POST 请求方法

put: PUT 请求方法

delete: DELETE 请求方法

完整代码如下:

index.ts:

复制代码
export class Request {
    private instance: AxiosInstance;
    private baseConfig: AxiosRequestConfig = { baseURL: BASE_URL, timeout: 60000 };

    public constructor(config: AxiosRequestConfig) {
        this.instance = axios.create(Object.assign(this.baseConfig, config));

        this.instance.interceptors.request.use(
            (config: any) => {
                // 配置处理逻辑
                // const token = 'tokentoken';
                return config;
            },
            (error: any) => {
                return Promise.reject(error);
            }
        )
        this.instance.interceptors.response.use(
            (res: any) => {
                if(res.data.code === 200) {
                    return res.data.data;
                }else {
                    // 错误code处理
                    return "发生错误";
                }
            },
            (error: any) => {
                return Promise.reject(error);
            }
        )
    }

    public request<T = any>(config: AxiosRequestConfig): Promise<T> {
        return this.instance.request(config);
    }

    public get<T = any>(url: string, params?: any, config?: AxiosRequestConfig): Promise<T> {
        return this.instance.get(url, {params, ...config});
    }

    public post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
        return this.instance.post(url, data, config);
    }

    public put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
        return this.instance.put(url, data, config)
    }

    public delete<T = any>(url: string, params?: any, config?: AxiosRequestConfig): Promise<T> {
        return this.instance.delete(url, {params, ...config});
    }

}

6、创建实例,并导出为Axios

复制代码
export const Axios = new Request({
    baseURL: BASE_URL,
});

7、使用

a)、封装一个HTTP请求

example.ts:

复制代码
import { Axios } from '@/api'

export function HTLLOWORD() {
    return Axios.get<any>('/json/example.json')
}

example.json:

复制代码
{   
    "code": 200,
    "data": "hello word"
}

b)、调用

复制代码
import { HTLLOWORD } from '@/api/example'

const getTest = () => {
  HTLLOWORD().then(res => {
    console.log(res)
  })
}

getTest();
相关推荐
AI自动化工坊1 小时前
Late框架技术深度解析:5GB VRAM实现10倍AI编码效率的工程架构
人工智能·5g·架构·ai编程·late
空中海1 小时前
第六篇:架构篇 — 微服务、部署、高并发与专家级能力
微服务·云原生·架构
Wave8452 小时前
基于 STM32 + ESP8266 + W25Q64 的双核 OTA 底层架构总结
stm32·嵌入式硬件·架构
yongyoudayee3 小时前
CRM架构演进:从记录系统到执行引擎的技术解析
架构
源码宝3 小时前
基于 SpringBoot + Vue 的医院随访系统:技术架构与功能实现
java·vue.js·spring boot·架构·源码·随访系统·随访管理
有马贵将4 小时前
【5】微前端知识点总结
前端·架构
ting94520004 小时前
深入解析 Social Fetch 机制:原理、架构、应用场景、实战落地与性能优化全攻略
人工智能·性能优化·架构
ZOOOOOOU4 小时前
云边端协同架构下,门禁权限引擎的离线决策与策略续存实现
大数据·人工智能·架构
heimeiyingwang5 小时前
【架构实战】编排vs协同:微服务通信架构选型
微服务·云原生·架构
ai产品老杨6 小时前
深度解析:基于国产化异构计算的 AI 视频管理平台架构——从 GB28181 接入到 NPU 边缘推流的解耦实践
人工智能·架构·音视频