当前位置:   article > 正文

VUE3 + TS 使用 Axios(copy可直接使用)_ts对axios响应结果进行处理

ts对axios响应结果进行处理

index.ts 用来暴露实例

  1. import EnclosureHttp from "@/utils/http/requset";
  2. const http = new EnclosureHttp();
  3. export default http;

 request.ts 实现 axios 创建实例 请求拦截 响应拦截 和默认 的get post 封装(偷懒了,没有封装自定义的 get post put delete )

  1. import Axios, {
  2. AxiosRequestConfig,
  3. AxiosResponse,
  4. AxiosError,
  5. AxiosInstance,
  6. } from "axios";
  7. import { Request } from "@/utils/http/types";
  8. import { ElMessage } from "element-plus";
  9. /**
  10. * 封装的 element-plus 的消息提示框
  11. * @param msg
  12. * @param type
  13. */
  14. const message = (msg: string, type?: string) => {
  15. ElMessage({
  16. message: msg,
  17. type: type || "warning",
  18. duration: 1500,
  19. });
  20. };
  21. /**
  22. * 默认 create Axios 的配置参数
  23. */
  24. const defaultConfig: AxiosRequestConfig = {
  25. baseURL: "",
  26. timeout: 10000, //10秒超时
  27. withCredentials: true,
  28. responseType: "json",
  29. transformRequest: [
  30. (data) => {
  31. //对请求的参数进行处理
  32. data = JSON.stringify(data);
  33. return data;
  34. },
  35. ],
  36. validateStatus() {
  37. // 使用async-await,处理reject情况较为繁琐,所以全部返回resolve,在业务代码中处理异常
  38. return true;
  39. },
  40. transformResponse: [
  41. (data) => {
  42. //对响应的数据进行处理
  43. if (typeof data === "string" && data.startsWith("{")) {
  44. data = JSON.parse(data);
  45. }
  46. return data;
  47. },
  48. ],
  49. headers: {
  50. Accept: "application/json, text/plain, */*",
  51. "Content-Type": "application/json",
  52. "X-Requested-With": "XMLHttpRequest",
  53. },
  54. };
  55. /**
  56. * Axios create的时候后去的配置参数
  57. * @param config
  58. */
  59. const getConfig = (config?: AxiosRequestConfig): AxiosRequestConfig => {
  60. if (!config) return defaultConfig;
  61. return defaultConfig;
  62. };
  63. /**
  64. * 自定义封装的Axios 类
  65. */
  66. class EnclosureHttp {
  67. constructor() {
  68. this.httpInterceptorsRequest();
  69. this.httpInterceptorsResponse();
  70. }
  71. /**
  72. * Axios 实例
  73. * @private
  74. */
  75. private static axiosInstance: AxiosInstance = Axios.create(getConfig());
  76. /**
  77. * 请求拦截
  78. * @private
  79. */
  80. private httpInterceptorsRequest(): void {
  81. EnclosureHttp.axiosInstance.interceptors.request.use(
  82. (config: AxiosRequestConfig) => {
  83. /*
  84. * 在请求发出去之前作出一下处理
  85. * */
  86. // console.log("config=>:", config);
  87. return config;
  88. },
  89. (err) => {
  90. return Promise.resolve(err);
  91. }
  92. );
  93. }
  94. /**
  95. * 响应拦截
  96. * @private
  97. */
  98. private httpInterceptorsResponse(): void {
  99. EnclosureHttp.axiosInstance.interceptors.response.use(
  100. (response: AxiosResponse) => {
  101. /*
  102. * 对响应的数据作出一些处理
  103. * */
  104. const { status } = response;
  105. let msg = "";
  106. if (status < 200 || status >= 300) {
  107. // 处理http错误,抛到业务代码
  108. if (typeof response.data === "string") {
  109. msg = "打盹了!!!";
  110. response.data = { msg };
  111. } else {
  112. response.data.msg = msg;
  113. }
  114. }
  115. return response;
  116. },
  117. (error: AxiosError) => {
  118. //请求出错的验证
  119. const { response } = error;
  120. if (response) {
  121. // 请求已发出,但是不在2xx的范围
  122. this.errorHandle(response.status, response.data.message);
  123. return Promise.reject(response);
  124. } else {
  125. // 处理断网的情况
  126. // eg:请求超时或断网时,更新state的network状态
  127. // network状态在app.vue中控制着一个全局的断网提示组件的显示隐藏
  128. // 后续增加断网情况下做的一些操作
  129. return Promise.reject(error);
  130. }
  131. }
  132. );
  133. }
  134. /**
  135. * 请求失败后的错误统一处理
  136. * @param status 请求失败的状态码
  137. * @param other
  138. */
  139. private errorHandle = (status: number, other: string) => {
  140. // 状态码判断
  141. switch (status) {
  142. case -1: // -1: 未登录状态,跳转登录页
  143. message("未登录状态");
  144. break;
  145. case 403: // 403 token过期
  146. message("登录过期,请重新登录");
  147. break;
  148. case 404: // 404请求不存在
  149. message("请求错误!!!");
  150. break;
  151. default:
  152. message(other);
  153. }
  154. };
  155. /**
  156. * get方法
  157. * @param url 路径
  158. * @param params 参数
  159. * @param config
  160. */
  161. public reqGet: Request = async (
  162. url: string,
  163. params?: unknown,
  164. config?: AxiosRequestConfig
  165. ) => {
  166. return await EnclosureHttp.axiosInstance.get(url, { params, ...config });
  167. };
  168. /**
  169. * post 方法
  170. * @param url 路径
  171. * @param params 参数
  172. * @param config
  173. */
  174. public reqPost: Request = (
  175. url: string,
  176. params: unknown = {},
  177. config?: AxiosRequestConfig
  178. ) => {
  179. return EnclosureHttp.axiosInstance.post(url, { data: params }, config);
  180. };
  181. /**
  182. * Axios init GET方法
  183. * @param url 路径
  184. * @param params 参数
  185. * @param config
  186. */
  187. public get: Request = (
  188. url: string,
  189. params?: unknown,
  190. config?: AxiosRequestConfig
  191. ) => {
  192. return Axios.get(url, { params, ...config });
  193. };
  194. /**
  195. * Axios init POST 方法
  196. * @param url 路径
  197. * @param params 参数
  198. * @param config
  199. */
  200. public post: Request = (
  201. url: string,
  202. params: unknown = {},
  203. config?: AxiosRequestConfig
  204. ) => {
  205. return Axios.post(url, { data: params }, config);
  206. };
  207. }
  208. export default EnclosureHttp;

type.ts  是类型和接口文件

  1. import { AxiosRequestConfig } from "axios";
  2. export interface IUser {
  3. name: string;
  4. pasword: string;
  5. }
  6. // 定制业务相关的网络请求响应格式, T 是具体的接口返回类型数据
  7. export interface CustomSuccessData<T> {
  8. status: number;
  9. statusText: string;
  10. message?: string;
  11. data: T;
  12. [keys: string]: unknown;
  13. }
  14. /**
  15. *
  16. */
  17. export interface Request {
  18. <T>(
  19. url: string,
  20. params?: Record<string, unknown>,
  21. config?: AxiosRequestConfig
  22. ): Promise<CustomSuccessData<T>>;
  23. }

最后实际使用:拿网易云API 举例 

cloudMusic.ts 

  1. import http from "@/utils/http";
  2. import { Klyric, Rows, Songs } from "@/api/cloudMusic/types.ts";
  3. const cloudBaseUrl = "https://autumnfish.cn/";
  4. // const cloud = "/api";
  5. /**
  6. * 网易云音乐开放接口的数据
  7. */
  8. export class CloudApi {
  9. /*
  10. * 搜索音乐
  11. * @Params: {keywords} : 关键字
  12. * */
  13. static async searchMusic(params: { keywords: string }): Promise<Rows<Songs>> {
  14. const res = await http.reqGet<Rows<Songs>>(
  15. cloudBaseUrl + `/search`,
  16. params
  17. );
  18. return res.data;
  19. }
  20. /*
  21. * 获取音乐详情
  22. * @Params: {ids} : 音乐ID
  23. * */
  24. static async searchMusicDetail(params: { ids: number }) {
  25. return await http.reqGet(cloudBaseUrl + `/song/detail`, params);
  26. }
  27. /*
  28. * 获取歌词
  29. * @Params: {id} : 音乐ID
  30. * */
  31. static async getMusicLyric(params: { id: number }): Promise<Klyric> {
  32. const res = await http.reqGet<Klyric>(cloudBaseUrl + `/lyric`, params);
  33. return res.data;
  34. }
  35. /*
  36. * 获取音乐 -- 暂不可用
  37. * @Params: {id} : 音乐的ID
  38. * */
  39. static async getMusicUrl(params: { id: number }): Promise<unknown> {
  40. const res = await http.reqGet(cloudBaseUrl + `/song/url`, params);
  41. return res.data;
  42. }
  43. }

types.ts 类型和接口

  1. //搜索音乐 接口返回的数据类型
  2. export interface Rows<T> {
  3. result?: Result<T>;
  4. code: number;
  5. }
  6. /**
  7. *搜索音乐返回的数据类型
  8. */
  9. type Result<T> = {
  10. hasMore: boolean;
  11. songCount: number;
  12. songs: Array<T>;
  13. };
  14. /*
  15. * 获取的音乐列表
  16. * */
  17. export interface Songs {
  18. album: album;
  19. alias: Array<string>;
  20. artists: Array<artist>;
  21. copyrightId: number;
  22. duration: number;
  23. fee: number;
  24. ftype: number;
  25. id: number;
  26. mark: number;
  27. mvid: number;
  28. name: string;
  29. rUrl: unknown;
  30. rtype: number;
  31. status: number;
  32. }
  33. /*
  34. * //
  35. * */
  36. type album = {
  37. artist: Array<artist>;
  38. copyrightId: number;
  39. id: number;
  40. mark: number;
  41. name: string;
  42. picId: number;
  43. publishTime: number;
  44. size: number;
  45. status: number;
  46. };
  47. /*
  48. * //
  49. * */
  50. type artist = {
  51. albumSize: number;
  52. alias: Array<unknown>;
  53. id: number;
  54. img1v1: number;
  55. img1v1Url: string;
  56. name: string;
  57. picId: number;
  58. picUrl: string;
  59. trans: string | number;
  60. };
  61. export interface Klyric {
  62. code: number;
  63. klyric: Lrc;
  64. lrc: Lrc;
  65. qfy: boolean;
  66. sfy: boolean;
  67. sgc: boolean;
  68. tlyric: Lrc;
  69. }
  70. export interface Lrc {
  71. lyric: string;
  72. version: number;
  73. }

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

闽ICP备14008679号