ajax_fetch_request
使用 Fetch API 发出请求
Section titled “使用 Fetch API 发出请求”fetch() API 是用于在浏览器(以及 Node.js 等其他环境)中发出异步 HTTP 请求的现代、基于 Promise 的标准。它取代了旧的 XMLHttpRequest 对象,提供了更简洁、更强大的接口。
基本 Fetch 请求 (GET)
Section titled “基本 Fetch 请求 (GET)”fetch() 的最简单用法接受一个参数:您希望获取的资源的 URL。默认情况下,它会发出一个 GET 请求。
fetch() 返回一个 Promise,该 Promise 在请求成功或失败时解析为 Response 对象。您将在下一章节学习如何处理响应。
// Basic GET requestfetch('https://api.example.com/users') // URL of the API endpoint or resource .then(response => { // First step: check if the request was successful (status code 200-299) if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } // Second step: parse the response body (e.g., as JSON) return response.json(); // returns another promise }) .then(data => { // Third step: use the parsed data console.log('Data received:', data); }) .catch(error => { // Handle network errors or errors thrown in the .then() blocks console.error('Fetch error:', error); });
// Using async/await (often preferred for readability)async function fetchData(url) { try { const response = await fetch(url); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); console.log('Data received (async/await):', data); } catch (error) { console.error('Fetch error (async/await):', error); }}
fetchData('https://api.example.com/users');注意:fetch() 仅在网络故障(例如 DNS 错误、无连接)时才会拒绝其 Promise。像 404(未找到)或 500(服务器错误)这样的 HTTP 错误状态码不会导致 Promise 被拒绝。您必须手动检查 response.ok 或 response.status。
使用选项配置请求
Section titled “使用选项配置请求”fetch() 可以接受一个可选的第二个参数,一个 init 对象,用于自定义请求(方法、头部、主体等)。
| 选项 | 描述 |
|---|---|
method | HTTP 请求方法,例如 ‘GET’(默认)、‘POST’、‘PUT’、‘DELETE’、‘PATCH’、‘HEAD’。 |
headers | 包含请求头部的对象或 Headers 对象,例如 { 'Content-Type': 'application/json', 'Accept': 'application/json' }。 |
body | 请求主体。可以是字符串、Blob、BufferSource、FormData、URLSearchParams 或 ReadableStream。必须与 Content-Type 头部匹配。常与 POST、PUT、PATCH 一起使用。 |
mode | 控制跨域请求的处理方式,例如 ‘cors’(默认)、‘no-cors’、‘same-origin’。 |
cache | 控制请求如何与浏览器 HTTP 缓存交互,例如 ‘default’、‘no-store’、‘reload’。 |
credentials | 控制请求是否发送 Cookie,例如 ‘include’、‘same-origin’(默认)、‘omit’。 |
GET vs. POST
Section titled “GET vs. POST”GET:用于请求指定资源的数据。数据通常通过 URL 查询参数发送。不应改变服务器状态(幂等)。请求可以被缓存和书签。
POST:用于提交数据到指定资源进行处理(例如,创建新项、提交表单)。数据在请求主体中发送。可以改变服务器状态。请求通常不会被缓存或书签。
带有查询参数的 GET 请求
Section titled “带有查询参数的 GET 请求”对于 GET 请求,数据通常附加在 URL 后面。
// Manually constructing the URLconst userId = 123;fetch(`/api/users/${userId}?include=profile&theme=dark`);
// Using URLSearchParams for safer encodingconst params = new URLSearchParams({ include: 'profile', theme: 'dark'});fetch(`/api/users/${userId}?${params.toString()}`);带有 JSON 主体的 POST 请求
Section titled “带有 JSON 主体的 POST 请求”要使用 POST 发送 JSON 数据:
- 将
method设置为'POST'。 - 将
Content-Type头部设置为'application/json'。 - 使用
JSON.stringify()将 JSON 数据(作为字符串)提供给body选项。
async function createUser(userData) { try { const response = await fetch('/api/users', { method: 'POST', // Specify the method headers: { 'Content-Type': 'application/json' // Indicate we're sending JSON }, body: JSON.stringify(userData) // Convert the JS object to a JSON string });
if (!response.ok) { // Handle potential errors (e.g., validation errors from the server) const errorData = await response.json().catch(() => ({ message: 'Unknown error' })); // Try to parse error details throw new Error(`Failed to create user: ${response.status} - ${errorData.message}`); }
const createdUser = await response.json(); // Get the newly created user data console.log('User created:', createdUser); return createdUser;
} catch (error) { console.error('Error creating user:', error); }}
const newUser = { name: 'Jane Doe', email: 'jane.doe@example.com' };createUser(newUser);跨域资源共享 (CORS)
Section titled “跨域资源共享 (CORS)”出于安全原因,浏览器限制网页向与其提供页面的来源(origin)不同的域(domain)发出请求。如果您的前端代码(例如在 mysite.com)试图从不同域(例如 api.externalservice.com)的 API 获取数据,浏览器将阻止该请求,除非 api.externalservice.com 的服务器在其响应中包含特定的 CORS 头部(例如 Access-Control-Allow-Origin)。
如果在浏览器控制台中遇到 CORS 错误,通常意味着服务器需要配置以允许来自您的前端来源的请求。这不是您通常仅在客户端能够解决的问题(除非使用 ‘no-cors’ 等模式,但它们有限制)。
在 MDN 上了解更多关于 fetch():https://developer.mozilla.org/en-US/docs/Web/API/fetch