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();
相关推荐
WanderInk42 分钟前
依赖对齐不再“失联”:破解 feign/BaseBuilder 错误实战
java·后端·架构
SoFlu软件机器人1 小时前
3 分钟生成 Spring Cloud 微服务架构,标准目录 + 依赖配置,开箱即用
spring cloud·微服务·架构
EyeDropLyq2 小时前
从 0 到 1 掌握 自研企业级分布式 ID 发号器
分布式·架构
前端付豪3 小时前
22、前端工程化深度实践:构建、发布、CI/CD 流程重构指南
前端·javascript·架构
啃火龙果的兔子4 小时前
nextjs+react项目如何代理本地请求解决跨域
前端·react.js·前端框架
泉城老铁5 小时前
springboot+vue实现快速文件上传详细指南
vue.js·后端·架构
Java技术小馆5 小时前
5种禁止用户复制的实用方案
java·面试·架构
不甘打工的程序猿5 小时前
nacos通讯方式学习《gRPC》
前端·架构
文火冰糖的硅基工坊7 小时前
[硬件电路-28]:从简单到复杂:宇宙、芯片与虚拟世界的共通逻辑
科技·架构·信号处理·电路·跨学科融合
步行cgn7 小时前
B/S 架构通信原理详解
架构