Files
admin/www/app/composables/useRequest.ts
T

39 lines
963 B
TypeScript
Raw Normal View History

/**
* 统一请求封装(基于 Nuxt 内置 ofetch
* 响应格式约定:{ code, data, message },成功码 '0000'
*/
interface ApiResponse<T = unknown> {
code: string;
data: T;
message: string;
}
export function useRequest() {
const config = useRuntimeConfig();
const baseURL = config.public.apiBaseUrl as string;
async function request<T = unknown>(url: string, options?: Parameters<typeof $fetch>[1]): Promise<T> {
const res = await $fetch<ApiResponse<T>>(url, {
baseURL,
...options
});
if (res.code !== '0000') {
throw new Error(res.message || 'Request failed');
}
return res.data;
}
function get<T = unknown>(url: string, params?: Record<string, unknown>) {
return request<T>(url, { method: 'GET', params });
}
function post<T = unknown>(url: string, body?: Record<string, unknown>) {
return request<T>(url, { method: 'POST', body });
}
return { request, get, post };
}