vue3加ts加antd 的http封装

33 阅读4分钟

封装http请求

安装 Axios

首先,您需要将 Axios 添加到您的项目中。您可以通过 npm 或 yarn 进行安装:

npm install axios

或者

yarn add axios

目录结构

image.png

index.ts

import axios from "axios";
import { notification } from "ant-design-vue";
import store from "@/store";
import router from "@/router";
// 获取环境变量
const env = import.meta.env;

// 创建 Axios 实例
const instance = axios.create({
    timeout: 120 * 1000, // 设置请求超时时间为 120 秒
    withCredentials: true, // 是否携带跨域请求的凭证
    baseURL: env.VITE_BASE_API_URL, // 设置基础请求 URL,使用环境变量
    headers: {
        "Content-Type": "application/json", // 设置请求头的 Content-Type
        "tenant-id": "", // 租户 ID,默认为空
    },
});
//请求拦截器
instance.interceptors.request.use(
    (config: any) => {
        // 每次发送请求之前判断是否存在token,如果存在,则统一在http请求的header都加上token,不用每次请求都手动添加了
        const token = window.localStorage.getItem("qyy_token");
        const tenantId = window.localStorage.getItem("tenantId");
        token && (config.headers.Authorization = `Bearer ${token}`);
        tenantId && (config.headers["tenant-id"] = tenantId);
        //若请求方式为post,则将data参数转为JSON字符串
        if (config.method === "POST") {
            config.data = JSON.stringify(config.data);
        }
        return config;
    },
    (error) =>
        // 对请求错误做些什么
        Promise.reject(error),
);

//响应拦截器
instance.interceptors.response.use(
    (response) => {
        const code: number = parseInt(response.data.code);
        if (code === 0) {
            //响应成功
            return response.data;
        } else if (code === 502 || code === 500) {
            notification.error({
                message: "后台系统繁忙...",
            });
        } else if (code == 577) {
            return response.data;
        } else {
            // 相应失败
            notification.error({
                message: response.data.msg || "响应失败",
            });
            if (code === 401 || code === 411 || code == 1002015000 || code == 1002015001 || code == 1002015002) {
                // 登录失效 执行退出登录操作并跳转至登录页
                store.dispatch("Logout").then(() => {
                    router.replace("/login");
                });
            }
            return response.data;
        }
    },
    (error) => {
        //响应错误
        if (error.code === "ECONNABORTED") {
            notification.error({
                message: "请求超时",
                description: "网络链接失败,请稍后再试!" || error.message,
            });
        } else {
            const status = error.response.status;
            console.log(`错误代码:${status}`);
            if (status === 500 || status === 502) {
                notification.error({
                    message: `后台系统繁忙...`,
                    description: status + "",
                });
            } else {
                notification.error({
                    message: `${error.code} ${status}`,
                    description: error.config.url,
                });
            }
        }
        return Promise.reject(error);
    },
);

export default instance;
```

download.ts 导出 下载请求模块 实现 格式

image.png

```
import axios from "axios";
import { notification } from "ant-design-vue";
import qs from "qs"; // 导入 qs 库,用于处理参数序列化
const env = import.meta.env; // 获取环境变量

// 创建一个名为 download 的 Axios 实例
const download = axios.create({
    timeout: 60000,
    baseURL: env.VITE_BASE_API_URL,
    headers: {
        "Content-Type": "application/json", // 设置请求头的 Content-Type 为 JSON 格式
        "tenant-id": "",
    },
    paramsSerializer: (params: any) => {
        return qs.stringify(params, { arrayFormat: "indices" }); // 序列化请求参数,使用 qs 库处理
    },
});
// 请求拦截器,在请求发送前做一些处理
download.interceptors.request.use(
    (config: any) => {
        const token = window.localStorage.getItem("qyy_token"); // 从本地存储获取 token
        const tenantId = window.localStorage.getItem("tenantId"); // 从本地存储获取租户 ID
        token && (config.headers.Authorization = `Bearer ${token}`); // 如果存在 token,则设置请求头的 Authorization
        tenantId && (config.headers["tenant-id"] = tenantId); // 如果存在租户 ID,则设置请求头的 tenant-id
        if (config.method === "post") {
            config.data = JSON.stringify(config.data); // 如果是 POST 请求,将请求体数据转换为 JSON 字符串
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    },
);
// 响应拦截器,在响应返回后做一些处理
// 响应拦截器,在响应返回后做一些处理
download.interceptors.response.use(
    (response) => {
        if (response && response.status == 200 && response.data) {
            // 如果响应状态码为 200,且存在响应数据
            const { data, config } = response; // 解构响应对象中的 data 和 config
            const { headers } = config; // 获取请求头
            const blob = new Blob([data], { type: "application/octet-stream" }); // 创建 Blob 对象
            const link = document.createElement("a"); // 创建 a 标签
            const currentDate = new Date(); // 获取当前日期时间
            const year = currentDate.getFullYear(); // 获取年份
            const month = (currentDate.getMonth() + 1).toString().padStart(2, "0"); // 获取月份,并补零
            const day = currentDate.getDate().toString().padStart(2, "0"); // 获取日期,并补零
            const hour = currentDate.getHours().toString().padStart(2, "0"); // 获取小时,并补零
            const minute = currentDate.getMinutes().toString().padStart(2, "0"); // 获取分钟,并补零
            const result = `${year}${month}${day}${hour}${minute}`; // 拼接日期时间字符串
            link.href = window.URL.createObjectURL(blob); // 设置链接的 href 属性为 Blob 对象的 URL
            const fileName = `${headers["fileName"] ? decodeURIComponent(headers["fileName"]) : "导出数据"}-${result}.xlsx`; // 获取文件名
            link.download = fileName; // 设置下载文件的名称
            link.click(); // 模拟点击链接进行下载
            link.remove(); // 移除链接
            return response; // 返回响应对象
        } else {
            return response; // 返回响应对象
        }
    },
    (error) => {
        // 响应错误处理
        if (error.code === "ECONNABORTED") {
            // 如果错误代码为请求超时
            notification.error({
                // 显示错误通知
                message: "请求超时",
                description: error.message,
            });
        } else {
            const status = error.response.status; // 获取响应状态码
            notification.error({
                // 显示错误通知
                message: `${error.code} ${status}`,
                description: error.config.url,
            });
        }
        return Promise.reject(error); // 返回 Promise 拒绝错误
    },
);

export default download;
```

axios.ts

```
import instance from "./index"; // 导入axios实例,
import download from "./download"; // 导入用于文件下载的axios实例
/**
 * @param {String} method  请求的方法:get、post、delete、put
 * @param {String} url     请求的url:
 * @param {Object} data    请求的参数
 * @param {Object} config  请求的配置
 * @returns {Promise}     返回一个promise对象,其实就相当于axios请求数据的返回值
 */
const axios = async ({ method, url, data, config }: any): Promise<any> => {
    method = method.toLowerCase(); // 将请求方法转换为小写
    if (method == "post") {
        return instance.post(url, data, { ...config }); // 使用axios实例的post方法发送请求
    } else if (method == "get") {
        // 如果是get请求
        return instance.get(url, {
            // 使用axios实例的get方法发送请求
            params: data, // 请求参数放在params中
            ...config, // 其他配置项
        });
    } else if (method == "delete") {
        // 如果是delete请求
        const p = { ...config }; // 复制config对象
        if (Array.isArray(data)) {
            // 如果参数是数组
            p.data = data; // 将参数放在data中
        } else {
            // 如果参数不是数组
            // 解决系统设置-二级企业管理-角色详情-删除 get请求参数为2时 参数放在在body
            if (Object.values(data).length > 1) {
                // 如果参数个数大于1
                p.data = data; // 将参数放在data中
            } else {
                // 如果参数个数不大于1
                p.params = data; // 将参数放在params中
            }
        }
        return instance.delete(url, p); // 使用axios实例的delete方法发送请求
    } else if (method == "put") {
        // 如果是put请求
        return instance.put(url, {
            // 使用axios实例的put方法发送请求
            ...data, // 请求参数
            ...config, // 其他配置项
        });
    }
};

const axiosDownload = async ({ method, url, data, config, headers }: any): Promise<any> => {
    method = method.toLowerCase(); // 将请求方法转换为小写
    if (method == "post") {
        // 如果是post请求
        return download.post(url, data, { ...config, responseType: "blob" }); // 使用download实例的post方法发送请求,设置响应类型为blob
    } else if (method == "get") {
        // 如果是get请求
        return download.get(url, {
            // 使用download实例的get方法发送请求
            params: data, // 请求参数放在params中
             ...config, // 其他配置项
            responseType: "blob", // 设置响应类型为blob
            headers: headers, // 设置请求头部信息
        });
    }
};
export { axios, axiosDownload };
```

使用

image.png

```
import { axios, axiosDownload } from "@/http/axios";

export const getBillPage = (data?: object) => {
    return axios({
        url: "/admin-api-saas/bill/details/getPage",
        data,
        method: "post",
    });
};

export const setBillExport = (data?: object, fileName?: string) => {
    return axiosDownload({
        url: "/admin-api-saas/bill/details/exportExcel",
        data,
        method: "get",
        headers: { fileName: fileName ? encodeURIComponent(fileName) : "" },
    });
};

export async function deleteDispatchOrder(data: any) {
    return axios({
        url: "/admin-api-saas/admin/sale-order/delete",
        method: "delete",
        data,
    });
}
export async function setDeliverLineupSetingEdit(data?:any) {
  return axios({
      url: '/admin-api-saas/admin/delivery-lineup-config/update',
      data,
      method: 'put'
  })
}

```

导出 使用

```
// 导出
//销售系统管理中心客户管理预付款管理 导出的名字
const exports = () => {
    exportSalePrePay({ customerId: props.info.id }, "销售系统管理中心客户管理预付款管理").then(() => {
        message.success("导出成功");
    });
};
```~~~