
当然,以下是关于 fetch 语法的详细文档。fetch 是一个用于在 JavaScript 中发起网络请求的现代 API,它返回一个 Promise 对象,使得处理异步请求变得更加简洁和直观。
基本语法
fetch(url, options) .then(response => { // 处理响应数据 if (!response.ok) { throw new Error('Network response was not ok ' + response.statusText); } return response.json(); // 或者其他解析方法如 .text(), .blob(), .formData() 等 }) .then(data => { // 使用获取的数据 console.log(data); }) .catch(error => { // 捕获并处理错误 console.error('There has been a problem with your fetch operation:', error); });参数说明
- url (字符串): 请求的资源地址。
- options (可选对象): 包含配置信息的对象,可以包括如下属性:
- method: HTTP 方法(例如 GET、POST)。
- headers: 一个 Headers 对象或一个包含键值对的对象,表示请求头信息。
- body: 请求的主体内容,可以是 Blob、BufferSource、FormData、URLSearchParams 或字符串等类型。如果设置了 Content-Type 为 'application/json',则通常传递一个 JSON 字符串。
- redirect: 指定如何处理重定向。可能的值有 'follow'(默认)、'error' 和 'manual'。
- signal: 一个 AbortSignal 对象,允许你取消请求。
- mode: 定义请求的模式,比如 'cors'(跨域资源共享),'no-cors'(不发送 CORS 头),'same-origin'(只允许同源请求)或 'navigate'(用于导航)。默认为 'cors'。
- credentials: 包括请求中携带的凭证信息,如 'omit'(默认值,不发送)、'same-origin'(仅同源请求时发送)或 'include'(总是发送)。
- cache: 请求的缓存模式,如 'default'、'no-store'、'reload'、'no-cache'、'force-cache' 或 'only-if-cached'。
- referrer: 设置请求的 referrer 信息。
- referrerPolicy: 设置 referrer 策略,如 'no-referrer', 'origin', 'unsafe-url' 等。
- keepalive: 保持网络连接活跃,直到请求完成(实验性功能)。
示例
GET 请求
fetch('https://api.example.com/data') .then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }) .then(data => console.log(data)) .catch(error => console.error('Fetch error:', error));POST 请求
const url = 'https://api.example.com/submit'; const data = { key: 'value' }; fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }) .then(result => console.log(result)) .catch(error => console.error('Fetch error:', error));错误处理
由于 fetch 返回的是一个 Promise,你可以使用 .catch() 方法来捕获和处理任何在请求过程中发生的错误,无论是网络问题还是服务器返回的错误状态码。
注意事项
- fetch 不会抛出错误,而是会返回一个被拒绝的 Promise,因此需要使用 .catch() 来处理错误。
- 对于不支持 fetch 的旧浏览器,可以使用 polyfill 库如 whatwg-fetch 来提供支持。
- 在处理敏感数据时,确保使用 HTTPS 协议来保护数据传输的安全性。
希望这份文档能帮助你更好地理解和使用 fetch 语法!
