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();
相关推荐
怕浪猫20 分钟前
2027 年最火的 AI 项目出炉,No.1 易主!
面试·架构·github
国科安芯2 小时前
把电源搬到负载身旁:ASP3605高频化设计与星载负载端电源架构
架构·adc·卫星·电源芯片·抗辐照芯片·在轨
Decay__4 小时前
PostgreSQL 运维自动化平台 —— 部署编排、监控、巡检、告警、工单闭环一体化
运维·数据库·sql·mysql·架构
一心同学6 小时前
深度拆解 DeepSeek Super-agent 的系统架构与工程取舍
ai·架构·agent·deepseek·super agent
HelloWorld00112 小时前
告警一天 800 条没人看:把 Prometheus 告警从噪音堆改成 5 条可行动的 SLO 告警
架构
微订校园外卖平台13 小时前
同城生活SaaS年费版架构评估:多商户订单状态机与结算链路拆解
架构·生活·外卖系统·本地生活·微订
Dawson Zhu13 小时前
【AI×半导体】09 虚拟量测(上):不测量,也能算出 CD 吗
人工智能·语言模型·架构·aigc·agi
计算机–阿拉升学长13 小时前
基于springBool+Vue美食分享平台 — 系统设计与实现
前端·vue.js·spring boot·mysql·vue·javaweb·美食
小盆女神节奶粉13 小时前
03-登录与RBAC
java·架构
Eyfcom14 小时前
〖物流自动化测试 03〗Chaos Mesh 在物流微服务中的故障注入:从 Pod 宕机到业务逻辑故障的工程实践
服务器·微服务·架构·快递系统·物流自动化测试