二次封装 fetch
API 是一种常见的做法,特别是在大型项目中,可以统一处理 HTTP 请求和响应。以下是一个使用 TypeScript 进行 fetch
二次封装的完整详细场景使用案例:
1. 创建基础的 fetch 封装
首先,创建一个基础的 fetch
封装,处理基本的 GET 和 POST 请求。
// src/utils/fetch.ts
import {
Response, RequestInit } from 'node-fetch';
const BASE_URL = 'https://api.example.com';
async function fetchApi<T>(url: string, options?: RequestInit): Promise<T> {
const response = await fetch(BASE_URL + url, options);
if (!response.ok) {
throw new Error(`HTTP error! status: ${
response.status}`);
}
return response.json() as Promise<T>;
}
export async function get<T>(url: string): Promise<T> {
return fetchApi<T>(url, {
method: 'GET' });
}
export async function post<T