http.ts 763 Bytes
export async function fetchJson<T>(input: RequestInfo | URL, init?: RequestInit): Promise<T> {
  const response = await fetch(input, {
    headers: {
      'Content-Type': 'application/json',
      ...(init?.headers ?? {}),
    },
    ...init,
  })

  const payload = await response.json().catch(() => ({}))
  if (!response.ok) {
    const message = (payload as { message?: string; error?: string }).message
      || (payload as { message?: string; error?: string }).error
      || `请求失败 (${response.status})`
    throw new Error(message)
  }

  return payload as T
}

export async function postJson<T>(input: RequestInfo | URL, body?: unknown): Promise<T> {
  return fetchJson<T>(input, {
    method: 'POST',
    body: JSON.stringify(body ?? {}),
  })
}