vue3+ts axios.request二次封装-通用模版

(感觉写的不是很好, 但是勉强能用,希望有大佬能够指点指点修改的地方...)
例:

使用:

//引入
import request "@/utils/request.ts"

// 使用
// {}传参
request({url,method,data})
// method 有get,GET,POST,post等等
request.method(url,data)
// url string类型,默认GET方式请求,不携带参数
request("url")

源码:

// 引入axios 和 提供的ts类型
import axios, {
    AxiosInstance,
    InternalAxiosRequestConfig,
    AxiosResponse,
    AxiosError,
    Method,
} from "axios";

// 创建axios实例对象
const instance: AxiosInstance = axios.create({
    baseURL: "",
    timeout: 3000,
    headers: {},
});

// 添加请求拦截器
instance.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        // 处理请求参数
        return config;
    },
    (error: AxiosError) => {
        // 对请求错误做些什么
        return Promise.reject(error);
    }
);

// 添加响应拦截器
instance.interceptors.response.use(
    (response: AxiosResponse) => {
        // 处理响应数据
        return response;
    },
    (error: AxiosError) => {
        return Promise.reject(error);
    }
);

// ps:提供了InternalAxiosRequestConfig请求类型,但是我偷个懒,直接写了一个RequestOptions
type RequestOptions = {
    url: string;
    method?: Method;
    data?: { [key: string]: any };
    headers?: { [key: string]: any };
    [key: string]: any;
};

// 为 request 函数定义一个扩展接口,允许动态方法属性
interface RequestFunction {
    (options: RequestOptions | string): Promise<AxiosResponse<any>>;
    [method: string]: any;
}
/**
 * 创建一个新的请求实例。
 * @param options - 请求选项或URL字符串。
 * @returns 返回一个Promise,解析为AxiosResponse对象。
 */
const request: RequestFunction = (options: RequestOptions | string): Promise<AxiosResponse<any>> => {
    let newOptions: RequestOptions = {
        url: "",
        method: "GET" as Method,
    };

    if (typeof options === "string") {
        newOptions.url = options;
    } else {
        newOptions = { ...options };
    }

    newOptions.method = newOptions.method?.toUpperCase() as Method || "GET";

    if (newOptions.method === "POST") {
        newOptions.headers = {
            ...newOptions.headers,
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
        };
    }

    if (newOptions.method === "GET" && newOptions.data) {
        newOptions.params = newOptions.data;
    }

    return instance(newOptions);
};
const methodList: Method[] = [
    "get",
    "GET",
    "delete",
    "DELETE",
    "head",
    "HEAD",
    "options",
    "OPTIONS",
    "post",
    "POST",
    "put",
    "PUT",
    "patch",
    "PATCH",
    "purge",
    "PURGE",
    "link",
    "LINK",
    "unlink",
    "UNLINK",
];

methodList.forEach((method) => {
    request[method] = (url: string, data?: { [key: string]: any }): Promise<AxiosResponse<any>> => {
        const options: RequestOptions = {
            method: method.toUpperCase() as Method,
            url,
            data,
        };

        return request(options);
    };
});

export default request;

  • 8
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
回答: 在Vue3中,可以使用TypeScript封装axios。下面是一个关于axios封装的示例代码: 引用中的代码展示了一个名为ZJRequest的类,这个类是对axios进行了封装。它包含了一个axios实例属性instance和一个request方法,用于发出请求。 引用中的代码展示了axios的拦截器的配置。其中,请求拦截器可以在发送请求前进行一些操作,比如设置请求头;响应拦截器则用于处理状态码等情况。这里使用了axios的create方法创建了一个实例对象myAxios,并对它进行了拦截器的设置。 引用给出了一个axios.get().then()这样的书写方式的缺点,即无法统一处理请求头。为了解决这个问题,可以在一个单独的文件夹中创建一个request.js文件,并在其中使用axios.create创建实例对象,在实例对象中设置请求和响应拦截器。 综上所述,可以在Vue3中使用TypeScriptaxios进行封装,以实现统一处理请求和响应的需求。123 #### 引用[.reference_title] - *1* [Vue3+TS封装axios](https://blog.csdn.net/qq_55928824/article/details/128548171)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}} ] [.reference_item] - *2* [vue3+TS封装axios](https://blog.csdn.net/m0_56561602/article/details/131600356)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}} ] [.reference_item] - *3* [vue3 +ts 安装并封装axios](https://blog.csdn.net/weixin_59916662/article/details/127336840)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值