共计 2314 个字符,预计需要花费 6 分钟才能阅读完成。
网络请求基础概念
HTTP 协议与请求方法
HTTP(HyperText Transfer Protocol)是互联网上应用最广泛的协议之一。它定义了客户端和服务器之间通信的规则。常见的 HTTP 请求方法包括:

- GET:获取资源
- POST:提交数据
- PUT:更新资源
- DELETE:删除资源
- PATCH:部分更新资源
状态码解析
HTTP 状态码表示请求的处理结果,主要分为以下几类:
- 2xx:成功(如 200 OK)
- 3xx:重定向(如 301 Moved Permanently)
- 4xx:客户端错误(如 404 Not Found)
- 5xx:服务器错误(如 500 Internal Server Error)
常见痛点分析
超时处理
网络请求可能会因为各种原因超时,良好的超时设置可以避免用户长时间等待。
// 设置超时示例
fetch(url, {signal: AbortSignal.timeout(5000) // 5 秒超时
}).catch(err => {if (err.name === 'TimeoutError') {console.log('请求超时');
}
});
错误重试机制
对于暂时性错误,合理的重试策略可以提高请求成功率。
async function fetchWithRetry(url, retries = 3) {for (let i = 0; i < retries; i++) {
try {const response = await fetch(url);
return await response.json();} catch (err) {if (i === retries - 1) throw err;
await new Promise(res => setTimeout(res, 1000 * (i + 1)));
}
}
}
技术方案对比
原生 fetch
现代浏览器内置的 API,但需要自行处理很多细节。
fetch(url)
.then(response => {if (!response.ok) throw new Error('Network response was not ok');
return response.json();})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
axios
功能更完善的第三方库,自动处理 JSON 转换,提供拦截器等高级功能。
axios.get(url)
.then(response => console.log(response.data))
.catch(error => console.error('Error:', error));
完整代码示例
封装请求函数
async function request(url, method = 'GET', data = null) {
const options = {
method,
headers: {'Content-Type': 'application/json',},
};
if (data) {options.body = JSON.stringify(data);
}
try {const response = await fetch(url, options);
if (!response.ok) {const error = await response.json();
throw new Error(error.message || '请求失败');
}
return await response.json();} catch (error) {console.error('请求错误:', error);
throw error;
}
}
性能优化建议
缓存策略
合理利用缓存可以减少不必要的网络请求。
// 使用 Cache API
caches.open('my-cache').then(cache => {cache.match(url).then(response => {if (response) {return response.json();
}
return fetch(url);
});
});
并发控制
对于批量请求,控制并发数量可以避免性能问题。
async function batchRequests(urls, maxConcurrent = 5) {const results = [];
for (let i = 0; i < urls.length; i += maxConcurrent) {const batch = urls.slice(i, i + maxConcurrent);
const batchResults = await Promise.all(batch.map(url => fetch(url)));
results.push(...batchResults);
}
return results;
}
生产环境避坑指南
安全考量
- 始终使用 HTTPS
- 验证和清理用户输入
- 使用 CSRF Token 防护
跨域问题
// 后端设置 CORS 头部
app.use((req, res, next) => {res.header('Access-Control-Allow-Origin', 'https://yourdomain.com');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
next();});
思考与实践
- 尝试实现一个带指数退避的重试机制
- 比较 fetch 和 axios 在错误处理上的差异
- 思考如何优化你项目中的网络请求代码
延伸学习
- WebSocket 实时通信
- GraphQL 数据查询
- RESTful API 设计规范
- HTTP/ 2 和 HTTP/ 3 特性
正文完
发表至: 编程开发
近一天内
