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

使用:

//引入
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;

Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐