mirror of
https://github.com/NapNeko/NapCatQQ.git
synced 2024-11-21 09:36:35 +00:00
refactor: HttpGetJson
This commit is contained in:
parent
317c6d96e3
commit
42ba524e4e
@ -18,4 +18,31 @@ export class RequestUtil {
|
|||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
}
|
static async HttpGetJson<T>(url: string, method: string = 'GET', data?: any, headers: Record<string, string> = {}):
|
||||||
|
Promise<T> {
|
||||||
|
let body: BodyInit | undefined = undefined;
|
||||||
|
let requestInit: RequestInit = { method: method };
|
||||||
|
|
||||||
|
if (method.toUpperCase() === 'POST' && data !== undefined) {
|
||||||
|
body = JSON.stringify(data);
|
||||||
|
if (headers) {
|
||||||
|
headers['Content-Type'] = 'application/json';
|
||||||
|
requestInit.headers = new Headers(headers);
|
||||||
|
} else {
|
||||||
|
requestInit.headers = new Headers({ 'Content-Type': 'application/json' });
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
requestInit.headers = new Headers(headers);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const response = await fetch(url, { ...requestInit, body });
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`HTTP error! status: ${response.status}`);
|
||||||
|
}
|
||||||
|
const jsonResult = await response.json();
|
||||||
|
return jsonResult as T;
|
||||||
|
} catch (error: any) {
|
||||||
|
throw new Error(`Failed to fetch JSON: ${error.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user