import { useFetch } from "#app"; import type { UseFetchOptions } from "#app"; import { isArray } from "~/utils/utils"; const useServerRequest = async ( url: string, opts?: UseFetchOptions ) => { const token = useCookie("token"); const runtimeConfig = useRuntimeConfig(); const defaultOptions: UseFetchOptions = { baseURL: runtimeConfig.public.apiBase, onRequest({ options }) { options.headers = options.headers || "application/json"; if (token.value) { // @ts-ignore options.headers["authorization"] = "Bearer " + token.value; } }, onResponse({ response }) { if (+response.status === 200 && +response._data.code !== 200) { process.client && ElMessage.error(response._data.msg); } }, onResponseError({ response }) { process.client && ElMessage.error( isArray(response._data.data.msg) ? response._data.data.msg[0] : response._data.data.msg ); }, }; // return useFetch(url, { ...defaultOptions, ...opts } as any); // 明确转换返回类型 const response = await useFetch(url, { ...defaultOptions, ...opts } as any); return response as unknown as T; }; // GET请求 export const get = ( endpoint: string, config?: Omit ): Promise => { return useServerRequest(endpoint, { ...config, method: 'GET' }) } // POST请求 export const post = ( endpoint: string, body?: any, config?: Omit ): Promise => { return useServerRequest(endpoint, { ...config, method: 'POST', body }) } // DELETE请求 export const del = ( endpoint: string, config?: Omit ): Promise => { return useServerRequest(endpoint, { ...config, method: 'DELETE' }) } // PUT请求 export const put = ( endpoint: string, body?: any, config?: Omit ): Promise => { return useServerRequest(endpoint, { ...config, method: 'PUT', body }) }