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

饭宝  金牌会员 | 2024-7-14 17:23:54 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 577|帖子 577|积分 1731

堆栈地点:https://github.com/buguniao5213/LuArch
1、安装axios

  1. npm install axios
复制代码
2、创建文件

先创建一个文件夹:
  1. ├── src/
  2. │   ├── api/        
  3. │   │   ├── index.ts/   #编写axios封装代码   
  4. │   │   └── example.ts/ #定义向后端服务器发送请求的模块`
复制代码
  1. ├── publix/
  2. │   ├── json/        
  3. │   │   └── example.json/   #模拟get接口获取到的数据`
复制代码
3、导入申明

导入axios库和干系类型
  1. import axios, { type AxiosInstance, type AxiosRequestConfig } from 'axios';
复制代码
4、基础url定义

这个后面放到vite的缓建变量配置中(.env)
  1. const BASE_URL = '/'
复制代码
5、定义request类

要素如下:
  1. export class Request {
  2.     private instance: AxiosInstance;
  3.     private baseConfig: AxiosRequestConfig = { baseURL: BASE_URL, timeout: 60000 };
  4.     public constructor() {
  5.         //...   
  6.     }
  7.     public request() {
  8.         //...   
  9.     }
  10.     public get() {
  11.         //...   
  12.     }
  13.    
  14.     //...
  15.     //...
  16. }
复制代码
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:
  1. export class Request {
  2.     private instance: AxiosInstance;
  3.     private baseConfig: AxiosRequestConfig = { baseURL: BASE_URL, timeout: 60000 };
  4.     public constructor(config: AxiosRequestConfig) {
  5.         this.instance = axios.create(Object.assign(this.baseConfig, config));
  6.         this.instance.interceptors.request.use(
  7.             (config: any) => {
  8.                 // 配置处理逻辑
  9.                 // const token = 'tokentoken';
  10.                 return config;
  11.             },
  12.             (error: any) => {
  13.                 return Promise.reject(error);
  14.             }
  15.         )
  16.         this.instance.interceptors.response.use(
  17.             (res: any) => {
  18.                 if(res.data.code === 200) {
  19.                     return res.data.data;
  20.                 }else {
  21.                     // 错误code处理
  22.                     return "发生错误";
  23.                 }
  24.             },
  25.             (error: any) => {
  26.                 return Promise.reject(error);
  27.             }
  28.         )
  29.     }
  30.     public request<T = any>(config: AxiosRequestConfig): Promise<T> {
  31.         return this.instance.request(config);
  32.     }
  33.     public get<T = any>(url: string, params?: any, config?: AxiosRequestConfig): Promise<T> {
  34.         return this.instance.get(url, {params, ...config});
  35.     }
  36.     public post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
  37.         return this.instance.post(url, data, config);
  38.     }
  39.     public put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
  40.         return this.instance.put(url, data, config)
  41.     }
  42.     public delete<T = any>(url: string, params?: any, config?: AxiosRequestConfig): Promise<T> {
  43.         return this.instance.delete(url, {params, ...config});
  44.     }
  45. }
复制代码
6、创建实例,并导出为Axios

  1. export const Axios = new Request({
  2.     baseURL: BASE_URL,
  3. });
复制代码
7、使用

a)、封装一个HTTP请求
example.ts:
  1. import { Axios } from '@/api'
  2. export function HTLLOWORD() {
  3.     return Axios.get<any>('/json/example.json')
  4. }
复制代码
example.json:
  1. {   
  2.     "code": 200,
  3.     "data": "hello word"
  4. }
复制代码
b)、调用
  1. import { HTLLOWORD } from '@/api/example'
  2. const getTest = () => {
  3.   HTLLOWORD().then(res => {
  4.     console.log(res)
  5.   })
  6. }
  7. getTest();
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

饭宝

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表