From 42ba524e4ec8f90799e863067db5f9132c2c606f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=89=8B=E7=93=9C=E4=B8=80=E5=8D=81=E9=9B=AA?= Date: Mon, 13 May 2024 17:53:50 +0800 Subject: [PATCH] refactor: HttpGetJson --- src/common/utils/request.ts | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/src/common/utils/request.ts b/src/common/utils/request.ts index ce269991..c49ba0c3 100644 --- a/src/common/utils/request.ts +++ b/src/common/utils/request.ts @@ -18,4 +18,31 @@ export class RequestUtil { return result; } -} + static async HttpGetJson(url: string, method: string = 'GET', data?: any, headers: Record = {}): + Promise { + 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}`); + } + } +} \ No newline at end of file