什么是Web标准Fetch API
[我严格遵守规则]
Web 标准 Fetch API
Fetch API 是浏览器和现代 Node.js (18+) 都内置的 HTTP 请求标准,由 WHATWG 制定,取代了老旧的 XMLHttpRequest。
核心对象一览
| 类/对象 | 作用 |
|---|---|
fetch() |
发起请求的全局函数 |
Request |
请求对象(URL、method、headers、body) |
Response |
响应对象(status、headers、body) |
Headers |
键值对的请求/响应头 |
URL |
URL 解析 |
URLSearchParams |
查询参数处理 |
FormData |
表单数据(文件上传等) |
AbortController |
取消请求 |
ReadableStream |
流式读取响应体(SSE / 大文件) |
基本使用
// ─── 最简单的 GET ───
const res = await fetch("https://api.example.com/users");
const data = await res.json(); // 解析 JSON
// ─── POST JSON ───
const res = await fetch("/api/auth/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email: "a@b.com", password: "123456" }),
});
const result = await res.json();
// ─── 带 Cookie(跨域时需要) ───
const res = await fetch("/api/auth/me", {
credentials: "include", // 自动携带 cookie
});
// ─── 上传文件 ───
const form = new FormData();
form.append("file", fileBlob, "photo.jpg");
const res = await fetch("/api/upload", {
method: "POST",
body: form, // 不要手动设 Content-Type,浏览器会自动加 boundary
});
Request 对象
// 两种用法等价:
fetch("/api/data", { method: "POST", body: "..." });
const req = new Request("/api/data", { method: "POST", body: "..." });
fetch(req);
Request 常用属性:
req.method; // "GET" | "POST" | ...
req.url; // 完整 URL
req.headers; // Headers 对象
req.body; // ReadableStream(原始流)
await req.json(); // 解析为 JSON
await req.text(); // 解析为字符串
await req.blob(); // 解析为二进制
await req.formData(); // 解析为 FormData
Response 对象
const res = await fetch(url);
res.ok; // true 当 status 200-299
res.status; // 200, 404, 500 等
res.statusText; // "OK", "Not Found" 等
res.headers; // Headers 对象
// 读取 body(只能读一次):
await res.json();
await res.text();
await res.blob();
await res.arrayBuffer();
// 手动构造(服务端常用,如 Next.js Route Handler):
new Response(JSON.stringify({ ok: true }), {
status: 200,
headers: { "Content-Type": "application/json" },
});
Headers 对象
const h = new Headers();
h.set("Authorization", "Bearer xxx");
h.get("Content-Type"); // 读取
h.has("Authorization"); // 判断存在
h.delete("X-Custom"); // 删除
h.forEach((val, key) => console.log(key, val)); // 遍历
AbortController — 取消请求
const controller = new AbortController();
// 3 秒超时
setTimeout(() => controller.abort(), 3000);
try {
const res = await fetch("/api/slow", {
signal: controller.signal,
});
} catch (e) {
if (e.name === "AbortError") {
console.log("请求被取消");
}
}
流式读取(SSE / AI 流式响应常用)
const res = await fetch("/api/chat");
const reader = res.body!.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
console.log(decoder.decode(value)); // 逐块输出
}
