封装axios请求

132 阅读2分钟

包装基础请求

http.ts

 /**axios封装
  * 请求拦截、相应拦截、错误统一处理
  */
 import axios from "axios";
 import type { AxiosRequestConfig } from "axios";
 ​
 // import QS from "qs";
 // import store from "../store/index";
 ​
 // 环境的切换
 // if (process.env.NODE_ENV === 'debug') {
 //     axios.defaults.baseURL = global.globalUrl
 //         // axios.defaults.baseURL = "/api"
 // } else if (process.env.NODE_ENV === 'production') {
 //     axios.defaults.baseURL = global.globalUrl
 //         // axios.defaults.baseURL = "/api"
 // }
 // axios.defaults.baseURL = "/api"
 // 为防止重新登录后,无法自动提交数据,定义变量,先将请求的数据存起来。
 ​
 axios.defaults.baseURL = "/";
 // 请求超时时间
 axios.defaults.timeout = 120000; //2分钟
 ​
 // post请求头
 axios.defaults.headers.post["Content-Type"] =
   "application/x-www-form-urlencoded;charset=UTF-8";
 ​
 // 请求拦截器
 axios.interceptors.request.use(
   (config) => {
     config.cancelToken = new cancelToken((c) => {
       addPending(config, c);
     });
     return config;
   },
   (error) => {
     return Promise.reject(error);
   }
 );
 ​
 // 响应拦截器
 axios.interceptors.response.use(
   (response) => {
     if (response.status === 200) {
       return Promise.resolve(response);
     } else {
       return Promise.reject(response);
     }
   },
   // 服务器状态码不是200的情况
   (error) => {
     console.log(error);
     if (error === "Error: Network Error") {
       alert("网络错误,请检查网络连接");
     } else if (error.response && error.response.status) {
       switch (error.response.status) {
         case 500:
           alert("请求不存在-500");
           break;
         case 404:
           alert("请求不存在-404");
           break;
         // 其他错误,直接抛出错误提示
         default:
           alert("其他错误,请检查网络");
           break;
       }
     }
     return Promise.reject(error.response);
   }
 );
 let pending: any[] = [];
 let cancels: any[] = [];
 const cancelToken = axios.CancelToken; // 初始化取消请求的构造函数
 const addPending = (config: any, fn?: any) => {
   if (pending.includes(config.url)) {
     let index = pending.indexOf(config.url);
     cancels.splice(index, 1, fn);
   } else {
     if (fn) {
       pending.push(config.url);
       cancels.push(fn);
     }
   }
 };
 /**
  *
  * @param url 请求地址
  * @param cancelMsg  取消提示信息
  */
 export function cancelApi(url: string, cancelMsg?: string) {
   if (pending.includes(url)) {
     let index = pending.indexOf(url);
     pending.splice(index, 1);
     let cancel = cancels.splice(index, 1)[0];
     // 提示 - 取消提示信息
     cancelMsg ? cancel(cancelMsg) : cancel();
   }
 }
 export function cancelAllApi() {
   pending = [];
   cancels.forEach((cancel) => cancel());
   cancels = [];
 }
 export enum Method {
   get = "get",
   GET = "GET",
   delete = "delete",
   DELETE = "DELETE",
   head = "head",
   HEAD = "HEAD",
   options = "options",
   OPTIONS = "OPTIONS",
   post = "post",
   POST = "POST",
   put = "put",
   PUT = "PUT",
   patch = "patch", //更新
   PATCH = "PATCH", //更新
   purge = "purge", //更新
   PURGE = "PURGE",
   link = "link",
   LINK = "LINK",
   unlink = "unlink",
   UNLINK = "UNLINK",
 }
 export function baseHttp(
   url: string,
   method: Method,
   config: AxiosRequestConfig & any
 ) {
   config.url = url;
   config.method = method;
   if (config.url?.indexOf("/") != 0) {
     config.url = "/" + config.url;
   }
   config.url = config.url.replace(////gi, "/");
   let sendConfig: object = {
     data: config.data ? config.data : config.params,
     params: config.params ? config.params : config.data,
   };
   sendConfig = Object.assign(config, sendConfig);
   return new Promise((resolve, reject) => {
     axios(sendConfig)
       .then((res) => resolve(res.data))
       .catch((e) => reject(e))
       .finally(() => {
         cancelApi(config.url);
       });
   });
 }
 export let get = (url: string, config: AxiosRequestConfig & any = {}) => {
   return baseHttp(url, Method.GET, config);
 };
 export function post(url: string, config: AxiosRequestConfig & any = {}) {
   return baseHttp(url, Method.POST, config);
 }
 export function put(url: string, config: AxiosRequestConfig & any = {}) {
   return baseHttp(url, Method.PUT, config);
 }
 export function del(url: string, config: AxiosRequestConfig & any = {}) {
   return baseHttp(url, Method.DELETE, config);
 }
 export function patch(url: string, config: AxiosRequestConfig & any = {}) {
   return baseHttp(url, Method.PATCH, config);
 }
 ​
 export default { get, post, put, del, patch, cancelApi, cancelAllApi };

index.ts

 import { get, post, put, del, patch, cancelApi, cancelAllApi } from "./http";
 ​
 export class Res {
   type;
   data;
   error;
   constructor(type: boolean = false, data: object = {}) {
     this.type = type;
     this.data = null;
     this.error = null;
     if (type) {
       this.data = data;
     } else {
       this.error = data;
     }
   }
 }
 // vue 在启动的时候会自动调用 install() 函数
 export default {
   install(app: any) {
     app.config.globalProperties.$get = get;
     app.config.globalProperties.$post = post;
     app.config.globalProperties.$put = put;
     app.config.globalProperties.$del = del;
     app.config.globalProperties.$patch = patch;
     app.config.globalProperties.$cancelApi = cancelApi;
     app.config.globalProperties.$cancelAllApi = cancelAllApi;
   },
 };

main.js

 import { createApp } from "vue"; 
 import App from "./App.vue";
 import http from "./http/http";
 import httpIndex from "./http/index";
 const app = createApp(App); 
 app.use(http as any);
 app.use(httpIndex); 
 app.mount("#app");