ajax_fetch_response
使用 Fetch 处理服务器响应
Section titled “使用 Fetch 处理服务器响应”Response 对象
Section titled “Response 对象”当一个 fetch 请求成功完成时,Promise 会以一个 Response 对象解析。这个对象包含关于响应的信息(例如 状态码 status code、响应头 headers)以及访问响应体 body 的方法。
重要提示:Response 对象不直接包含 body 数据。您需要调用它的一个读取 body 的方法,这些方法本身会返回 Promises。
Response 的关键属性:
Section titled “Response 的关键属性:”| 属性 | 描述 |
|---|---|
response.ok | 一个布尔值(boolean),表示 HTTP 状态码是否在成功范围内(200-299)。成功时返回 true,否则返回 false。 |
response.status | 响应的数字型 HTTP 状态码(例如 200、404、500)。 |
response.statusText | 与状态码对应的状态消息(例如 "OK"、"Not Found")。 |
response.headers | 一个 Headers 对象,允许您查询响应头(headers)(例如 response.headers.get('Content-Type'))。 |
response.url | 提供响应的资源的 URL(当发生重定向时很有用)。 |
检查是否成功
Section titled “检查是否成功”在尝试读取 body 之前,务必检查 response.ok。就网络通信而言,404(未找到 Not Found)或 500(内部服务器错误 Internal Server Error)响应仍然是 ‘成功’ 的 fetch 完成,但它不是一个成功的应用层级响应。
async function fetchData(url) { try { const response = await fetch(url);
if (!response.ok) { // 检查 HTTP 错误 // 您可以从 response.status 或 response.statusText 获取更具体的错误信息 throw new Error(`HTTP error! Status: ${response.status}`); }
// 仅在 response.ok 为 true 时继续 const data = await response.json(); // 或者 .text()、.blob() 等 console.log(data);
} catch (error) { // 这会捕获网络错误(fetch 失败)以及上面抛出的 HTTP 错误 console.error('Fetch error:', error); }}
fetchData('https://api.example.com/data');fetchData('https://api.example.com/nonexistent'); // 触发 404 的示例读取响应体 Body
Section titled “读取响应体 Body”Response 对象提供了多种方法来以不同格式读取 body。这些方法返回 Promises,它们会解析为实际的 body 内容。每个响应只能读取 body 一次。
| 方法 | 描述 |
|---|---|
response.json() | 读取响应体,并尝试将其解析为 JSON。返回一个 Promise,该 Promise 解析为结果的 JavaScript 对象或数组。 |
response.text() | 将响应体读取为纯文本。返回一个 Promise,该 Promise 解析为一个字符串。 |
response.blob() | 将响应体读取为 Blob(二进制大对象 Binary Large Object),适用于图像、文件等。返回一个 Promise,该 Promise 解析为 Blob。 |
response.formData() | 将响应体读取为 FormData。返回一个 Promise,该 Promise 解析为 FormData 对象。 |
response.arrayBuffer() | 将响应体读取为 ArrayBuffer(原始二进制数据 raw binary data)。返回一个 Promise,该 Promise 解析为 ArrayBuffer。 |
示例:读取 JSON
Section titled “示例:读取 JSON”这是与 Web API 协作时最常见的场景。
async function getUserData(userId) { try { const response = await fetch(`/api/users/${userId}`); if (!response.ok) { throw new Error(`Error fetching user: ${response.status}`); }
// 读取并解析 JSON body const userData = await response.json();
console.log('User Name:', userData.name); document.getElementById('userInfo').textContent = `User: ${userData.name}, Email: ${userData.email}`;
} catch (error) { console.error('Could not get user data:', error); document.getElementById('userInfo').textContent = 'Failed to load user data.'; }}
getUserData(123);示例:读取文本
Section titled “示例:读取文本”适用于获取 HTML 片段、纯文本文件或配置。
async function loadContent(url) { try { const response = await fetch(url); if (!response.ok) { throw new Error(`Failed to load content: ${response.status}`); }
// 将 body 读取为文本 const textContent = await response.text();
document.getElementById('contentArea').innerHTML = textContent; // 如果内容不可信,使用 innerHTML 时要小心
} catch (error) { console.error('Error loading content:', error); document.getElementById('contentArea').textContent = 'Could not load content.'; }}
loadContent('data/about.txt');常见陷阱:忘记在 body 方法上使用 await 或忘记检查 response.ok。
在 MDN 上了解更多关于 Response 对象的信息:https://developer.mozilla.org/en-US/docs/Web/API/Response