Files
admin/www/app/composables/useRequest.ts
T
2026-07-30 11:32:45 +08:00

39 lines
963 B
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 统一请求封装(基于 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 };
}