当前位置:   article > 正文

ts封装axios,并处理返回值_axios ts

axios ts
  • 本项目的案例是针对vue3

准备vue3+ts+axios的项目环境,这里不演示

src下新建所需文件夹及对应文件,如下图

文件信息

  • api 保存所有的接口列表及对应的返回数据类型
  • http 初始化axios,如果超时,设置拦截器等操作
  • axios 二次封装好的axios,供开发人员使用

设置api.ts,假设如下

/**
 * @description: 所有的接口列表
 * @param {*} 无参数
 * @return {*} 无返回值
 * ```js
 * key表示url路径缩写
 * value表示真实请求的路径
 * ```
 */
const apiList = {
  'getData': '/getData',
  'othersData': '/othersData'
}
/**
 * @description: 所有的接口列表类型
 * @param {*} 无参数
 * @return {*} 无返回值
 */
export type apiKeyType = keyof typeof apiList;
/**
 * @description: 接口对应的数据返回值类型
 * @param {*} 无参数
 * @return {*} 无返回值
 */
export interface apiKeyDataType {
  'getData': {
    code: number;
    data: {
      name: string;
      age: number;
      work: string[]
    }
  },
  'othersData': {
    code: number;
    data: string[]
  }
}

export default apiList;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40

设置http.ts

import axios, {Method, AxiosInstance, AxiosRequestConfig, AxiosPromise, AxiosInterceptorManager, AxiosResponse} from 'axios';
import qs from 'qs';
import {apiKeyType, apiKeyDataType} from './api';

type ResultDataType = apiKeyDataType[apiKeyType];
/* 
NewAxiosInstance接口得根据自己情况来定
  interceptors属性是必须要有,因为后续要用到拦截器
  至于<T = any>(config: AxiosRequestConfig): AxiosPromise<T>这一段代码,因为我后续二次封装axios时采用的是此类型,所以我这里
  声明的是这种数据类型
*/
interface NewAxiosInstance extends AxiosInstance {
  /* 
  设置泛型T,默认为any,将请求后的结果返回变成AxiosPromise<T>
  */
  <T = any>(config: AxiosRequestConfig): AxiosPromise<T>;
  interceptors: {
    request: AxiosInterceptorManager<AxiosRequestConfig>;
    response: AxiosInterceptorManager<AxiosResponse<ResultDataType>>;
  }
}

//基本的初始化设置
let http: NewAxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL as string, //因为使用的是vite构建的项目,所以这里是这么获取代理名称的,根据自己情况修改
  timeout: 3 * 1000// 超时时间
});

// 请求拦截器
const QS_METHOD: Method[] = ['POST', 'post', 'PUT', 'put'];
const GET_METHOD: Method[] = ['GET', 'get', 'DELETE', 'delete'];
http.interceptors.request.use(response => {
  if(response.method && QS_METHOD.includes(response.method)){// 这里只处理post请求,根据自己情况修改
    response.data = qs.stringify(response.data);
  }else if(response.method && GET_METHOD.includes(response.method)){//设置GET的请求参数
  	response.params = qs.parse(response.data);
  	response.data = undefined;
  }
  return response;
}, error => {
  return error;
});

//响应拦截器
http.interceptors.response.use(response => {
  return Promise.resolve(response);
}, error => {
  return error;
});

export default http;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51

设置axios.ts

import axios from '@/server/http';
import apiList, {apiKeyType, apiKeyDataType} from './api';
import {AxiosRequestConfig} from 'axios';

/* 
限制泛型T必须是接口列表(apiKeyType)中的key
限制obj中的url必须是接口列表中key的某一格
*/
export default <T extends apiKeyType>(obj: AxiosRequestConfig & {url: T}) => {
  /* 
  限制最终的返回数据类型
  */
  return new Promise<apiKeyDataType[T]>((resolve, reject) => {
    /* 
    传递泛型给http中的拦截器
    */
    axios<apiKeyDataType[T]>({
      url: apiList[obj.url],
      data: obj.data || {},
      method: obj.method || 'GET',
      responseType: obj.responseType || 'json'
    }).then(res => {
      resolve(res.data);
    }).catch(error => {
      reject(error);
    })
  })
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

最终效果

  • 在对应文件中引入server下的axios文件
  • 输入选择url时,将会有全部接口列表提示,如下图
    在这里插入图片描述
  • 选到getData时,可以看到返回值是对应的数据类型,如下
    在这里插入图片描述
  • 选到othersData时,可以看到返回如下
    在这里插入图片描述

结束

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/285725
推荐阅读
相关标签
  

闽ICP备14008679号