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();
相关推荐
xrkhy18 小时前
微服务之SpringCloud Alibaba(注册中心Nacos)
spring cloud·微服务·架构
虫小宝19 小时前
Java分布式架构下的电商返利APP技术选型与架构设计实践
java·分布式·架构
唐僧洗头爱飘柔952719 小时前
【SpringCloud(6)】Gateway路由网关;zuul路由;gateway实现原理和架构概念;gateway工作流程;静态转发配置
spring·spring cloud·架构·gateway·请求转发·服务降级·服务雪崩
白衣鸽子20 小时前
RPO 与 RTO:分布式系统容灾的双子星
后端·架构
WindrunnerMax20 小时前
从零实现富文本编辑器#8-浏览器输入模式的非受控DOM行为
前端·前端框架·github
一个处女座的暖男程序猿21 小时前
若依微服务 nacos的配置文件
微服务·云原生·架构
AI新兵21 小时前
AI大事记12:Transformer 架构——重塑 NLP 的革命性技术(下)
人工智能·架构·transformer
尘世中一位迷途小书童21 小时前
代码质量保障:ESLint + Prettier + Stylelint 三剑客完美配置
前端·架构
尘世中一位迷途小书童21 小时前
从零搭建:pnpm + Turborepo 项目架构实战(含完整代码)
前端·架构
java水泥工21 小时前
旅游管理系统|基于SpringBoot和Vue的旅游管理系统(源码+数据库+文档)
spring boot·vue·计算机毕业设计·java毕业设计·旅游管理系统