您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# fetch网络请求封装示例分析
## 引言
在现代Web开发中,网络请求是前端与后端交互的核心方式。`fetch`作为浏览器原生API,逐渐取代了传统的`XMLHttpRequest`。本文将通过一个完整的封装示例,分析如何基于`fetch`实现可复用、易维护的网络请求层。
## 一、基础封装实现
### 1.1 基本请求封装
```javascript
class HttpRequest {
static async request(method, url, data = null, headers = {}) {
const config = {
method,
headers: new Headers({
'Content-Type': 'application/json',
...headers
}),
};
if (data) {
config.body = JSON.stringify(data);
}
try {
const response = await fetch(url, config);
return await this._handleResponse(response);
} catch (error) {
throw this._handleError(error);
}
}
static async _handleResponse(response) {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
}
static _handleError(error) {
console.error('Request failed:', error);
return error;
}
}
const interceptors = {
request: [],
response: []
};
class HttpRequest {
static useRequestInterceptor(interceptor) {
interceptors.request.push(interceptor);
}
static async request(method, url, data, headers) {
// 执行请求拦截
for (const interceptor of interceptors.request) {
({ method, url, data, headers } =
await interceptor(method, url, data, headers));
}
// ...原有请求逻辑
}
}
功能 | 实现方案 |
---|---|
超时控制 | AbortController + setTimeout |
请求缓存 | Map结构存储已请求数据 |
重试机制 | 递归调用+最大重试次数限制 |
interface RequestConfig {
method: 'GET' | 'POST' | 'PUT' | 'DELETE';
url: string;
data?: unknown;
headers?: Record<string, string>;
timeout?: number;
}
interface Response<T = any> {
code: number;
data: T;
message: string;
}
static async get<T>(url: string): Promise<Response<T>> {
return this.request('GET', url);
}
export const UserAPI = {
login: (credentials) =>
HttpRequest.post('/api/login', credentials),
getProfile: () =>
HttpRequest.get('/api/user/profile')
};
async function fetchData() {
try {
const res = await UserAPI.getProfile();
setUserData(res.data);
} catch (err) {
showToast(err.message);
}
}
特性 | fetch封装 | axios |
---|---|---|
体积 | 小(无需额外依赖) | 较大 |
兼容性 | 需要polyfill | 更好 |
拦截器 | 需手动实现 | 内置 |
取消请求 | AbortController | CancelToken |
本文展示的fetch封装方案具有以下特点: - 分层清晰:基础请求/响应/错误处理分离 - 可扩展性强:通过拦截器机制支持各种定制需求 - 类型安全(TS版):完善的类型定义保障代码质量
完整实现代码已上传至GitHub仓库。
最佳实践建议:根据项目复杂度选择封装层级,中小型项目建议采用本文的基础封装,大型项目可考虑加入更多企业级功能如监控上报、自动化测试等。 “`
注:本文示例代码已简化,实际使用时需要根据项目需求进行调整。建议在封装时保留足够的灵活性,同时避免过度设计。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。