获取 API
Use 获取 API 到制作 HTTP 请求, handle 响应, and 工作使用异步/等待.
你将学到
- 如何获取() 制作 HTTP 请求 and 返回 Promise
- Using 异步/等待到 编写 clean asynchronous code
- Handling 错误: network failures 对比. HTTP 错误状态 codes
- 发送不同内容类型: JSON, 表单数据, and 请求头
概念讲解
Fetch API
The Fetch API is the modern, built-in way to make HTTP requests from JavaScript. It replaces the old XMLHttpRequest with a cleaner, promise-based interface. Whenever your web page needs to load data from a server — fetching a user profile, submitting a form, loading search results — 获取() is the tool. It is supported in all modern browsers and needs no library.
The Basics
获取(URL) makes a GET request and returns a Promise that resolves to a Response object:
const response = await fetch("https://api.example.com/users");
const data = await response.json();
The response is a stream — you must call .JSON(), .文本(), or .blob() to read the body. This two-step process (fetch, then parse) is because the headers are available immediately, but the body may still be downloading.
async/await
异步/等待 makes asynchronous code read like synchronous code. Mark a function 异步, then 等待 promises inside it. No more nested .然后() callbacks:
async function getUser(id) {
const response = await fetch(`/api/users/${id}`);
return response.json();
}
If a promise rejects (an error), 等待 throws — so wrap your code in try/catch to handle failures gracefully.
Error Handling
fetch only rejects on network failure — a DNS error, a dropped connection, a CORS block. It does not reject on HTTP error status codes (404, 500). A 404 response is a successful fetch that happens to contain an error. You must check response.ok (true for 2xx status codes) or response.status yourself:
if (!response.ok) {
throw new Error(`HTTP ${响应.状态}`);
}
Forgetting this is the most common fetch bug — your code silently treats an error response as success.
Sending Data
To send data (POST, PUT, etc.), pass a second argument with options:
fetch(url, {
method: "POST",
headers: { "内容-类型": "application/JSON" },
body: JSON.stringify({ name: "Ada" })
});
The 请求体 must be a string. For JSON, set the Content-Type header and stringify the body. For file uploads, use FormData instead of JSON.
示例代码
// A complete data-fetching function with error handling
async function fetchUsers(page = 1) {
try {
const response = await fetch(`https://api.example.com/users?page=${page}`, {
headers: { "Accept": "application/json" }
});
// fetch does NOT throw on 404/500 — check manually
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
return data.users;
} catch (error) {
// Network failure OR our thrown error lands here
console.error("Failed to fetch users:", error.message);
return []; // return a safe fallback
}
}
// POST with a JSON body
async function createUser(userData) {
const response = await fetch("https://api.example.com/users", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${getToken()}`
},
body: JSON.stringify(userData)
});
if (!response.ok) throw new Error("Create failed");
return response.json();
}
fetchUsers handles 两者都 network 错误 (caught 通过 try/catch) and HTTP 错误 (检查通过响应.好的). 它返回 safe fallback on 失败. createUser 发送 POST 使用 JSON 请求体 and 认证请求头. two-步骤模式 — 获取, 然后检查好的, 然后 parse — 是正确方式到 use 获取.
动手试一试
- JSON Formatter
API 响应是 JSON — 格式 and inspect 什么你的获取 calls 返回.
- JWT Decoder
获取 calls 经常发送 JWT 令牌 in 授权请求头 — decode one 到 inspect.
常见错误
错误写法
Assuming 获取 throws on 404 or 500 响应.
正确做法
获取仅 拒绝 on network 失败. HTTP 错误响应 (4xx, 5xx) still resolve successfully. 总是检查响应.好的 or 响应.状态 and throw manually 到 handle HTTP 错误.
错误写法
Forgetting 到设置内容-类型: application/JSON 当发送 JSON 请求体.
正确做法
如果你 发送 JSON.stringify(数据) as 请求体, 你必须设置请求头: { '内容-类型': 'application/JSON' }. 不使用它, 服务器做 不 know 到 parse 请求体 as JSON and 可能拒绝请求.
相关资源
相关速查表
- JavaScript Cheatsheet
引用 for 获取, 异步/等待, and Promise handling.
练习 获取 API
7 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。