开发者必知的 10 个 Fetch Standard 最佳实践
【免费下载链接】fetch Fetch Standard 项目地址: https://gitcode.com/gh_mirrors/fetc/fetch
Fetch Standard 作为现代 Web 开发的核心 API,为网络请求提供了强大而灵活的接口。本文将分享 10 个实用的 Fetch 最佳实践,帮助开发者写出更高效、更健壮的网络请求代码。无论是处理请求头、管理凭据还是处理错误,这些技巧都能让你的 Fetch 调用更加专业。
1. 掌握请求模式(mode)配置
Fetch API 的请求模式决定了跨域请求的行为,合理设置模式能有效避免常见的跨域问题。根据项目需求选择合适的模式:
- cors:允许跨域请求,仅返回 CORS 允许的响应头
- no-cors:限制跨域请求只能使用简单方法和头,返回不透明响应
- same-origin:只允许同源请求,跨域请求会被拒绝
示例代码:
// 跨域请求配置
fetch("https://api.example.com/data", { mode: "cors" })
.then(response => response.json())
.then(data => console.log(data));
2. 正确处理凭据(credentials)
凭据管理对于需要身份验证的应用至关重要。Fetch 提供了三种凭据模式,根据场景选择:
- omit:不发送凭据(默认)
- same-origin:仅在同源请求中发送凭据
- include:在所有请求中都发送凭据,包括跨域请求
最佳实践是显式设置凭据模式,避免默认行为导致的意外:
// 跨域请求包含凭据
fetch("https://api.example.com/user", {
credentials: "include"
})
.then(response => response.json());
3. 实现请求取消(AbortController)
长时间运行的请求可能需要支持取消功能,使用 AbortController 可以优雅地取消 Fetch 请求:
const controller = new AbortController();
const signal = controller.signal;
// 5秒后取消请求
setTimeout(() => controller.abort(), 5000);
fetch("https://api.example.com/large-data", { signal })
.then(response => response.json())
.catch(error => {
if (error.name === "AbortError") {
console.log("请求已取消");
}
});
4. 合理设置重定向(redirect)策略
Fetch 提供了三种重定向处理模式,根据需求选择适当的策略:
- follow:自动跟随重定向(默认)
- error:遇到重定向时抛出错误
- manual:手动处理重定向,通过 response.url 获取重定向地址
示例:处理手动重定向
fetch("/old-path", { redirect: "manual" })
.then(response => {
if (response.type === "opaqueredirect") {
console.log("重定向地址:", response.url);
// 手动处理重定向
return fetch(response.url);
}
return response;
});
5. 优化请求头(headers)设置
合理配置请求头可以提高 API 交互效率,常见的优化包括:
- 设置合适的 Content-Type
- 添加认证信息
- 配置缓存控制
示例:发送 JSON 数据并设置认证头
fetch("https://api.example.com/data", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + token
},
body: JSON.stringify({ key: "value" })
})
.then(response => response.json());
6. 完善的错误处理机制
Fetch 不会对 HTTP 错误状态码(如 4xx、5xx)抛出异常,需要手动检查响应状态:
fetch("https://api.example.com/data")
.then(response => {
if (!response.ok) {
throw new Error(`HTTP错误: ${response.status}`);
}
return response.json();
})
.catch(error => {
console.error("请求失败:", error);
// 实现错误恢复或用户提示
});
7. 使用 HEAD 方法优化资源检查
对于只需要检查资源是否存在或获取元数据的场景,使用 HEAD 方法可以减少数据传输:
// 检查资源是否存在
fetch("/document.pdf", { method: "HEAD" })
.then(response => {
if (response.ok) {
console.log("资源存在");
} else {
console.log("资源不存在");
}
});
8. 流式处理大型响应
对于大型响应体,使用流式处理可以提高性能并减少内存占用:
fetch("https://api.example.com/large-data")
.then(response => {
const reader = response.body.getReader();
return new ReadableStream({
start(controller) {
function read() {
reader.read().then(({ done, value }) => {
if (done) {
controller.close();
return;
}
controller.enqueue(value);
read();
});
}
read();
}
});
})
.then(stream => new Response(stream))
.then(response => response.blob())
.then(blob => {
// 处理获取的大型数据
});
9. 缓存策略优化
合理配置缓存模式可以减少不必要的网络请求,提高应用性能:
- default:使用标准的 HTTP 缓存规则
- no-store:完全不缓存
- reload:从服务器重新获取,不使用缓存
- no-cache:使用缓存前先验证
- force-cache:强制使用缓存,不验证
示例:强制从服务器获取最新数据
fetch("https://api.example.com/updates", { cache: "reload" })
.then(response => response.json())
.then(data => console.log("最新数据:", data));
10. 封装可复用的 Fetch 函数
将常用的 Fetch 配置封装为可复用的函数,可以提高代码质量和开发效率:
async function fetchData(url, options = {}) {
const defaultOptions = {
method: "GET",
headers: {
"Content-Type": "application/json"
},
credentials: "same-origin",
cache: "default"
};
const mergedOptions = { ...defaultOptions, ...options };
if (mergedOptions.body && typeof mergedOptions.body !== "string") {
mergedOptions.body = JSON.stringify(mergedOptions.body);
}
try {
const response = await fetch(url, mergedOptions);
if (!response.ok) {
throw new Error(`HTTP错误: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error("请求失败:", error);
throw error; // 重新抛出以便调用者处理
}
}
// 使用示例
fetchData("https://api.example.com/data", { method: "POST", body: { key: "value" } })
.then(data => console.log(data))
.catch(error => {
// 处理错误
});
总结
Fetch Standard 提供了强大的网络请求能力,通过掌握这些最佳实践,开发者可以编写出更高效、更可靠的网络请求代码。从正确配置请求模式和凭据,到实现请求取消和错误处理,每一个技巧都能帮助你构建更好的 Web 应用。记住,良好的 Fetch 使用习惯不仅能提升性能,还能增强代码的可维护性和用户体验。
在实际项目中,建议参考 fetch.bs 规范文档,深入了解 Fetch API 的全部功能,以便更好地应对各种复杂的网络请求场景。
【免费下载链接】fetch Fetch Standard 项目地址: https://gitcode.com/gh_mirrors/fetc/fetch
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考



