Skip to content

Fetch

介绍

Fetch API 是现代浏览器中用于发起网络请求的接口,具有以下特点:

  • 现代 API:Fetch 是现代的 Web API,提供了更简单和强大的方式来进行网络请求。
  • Promise 风格:Fetch 基于 Promise,使异步代码更易管理,支持流式操作。
  • 内置 JSON 支持:Fetch 内置支持 JSON 解析,响应对象是一个 Response 对象,可以使用内置方法进行处理。
  • 不支持老浏览器:不支持 Internet Explorer 11 及更早版本的浏览器,需要使用 polyfill 进行兼容性处理。

示例

read list

js
fetch('https://api.example.com/items')
  .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('There has been a problem with your fetch operation:', error)
  })

create

js
fetch('https://api.example.com/items', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ name: 'New Item' }),
})
  .then((response) => {
    if (!response.ok) {
      throw new Error('Network response was not ok')
    }
    return response.json()
  })
  .then((data) => {
    console.log('Item created:', data)
  })
  .catch((error) => {
    console.error('There has been a problem with your fetch operation:', error)
  })

常见问题

XHR vs Fetch

功能点XHRFeatch
基本的请求能力
基本的获取响应能力
监控请求进度
监控响应进度
Service Worker 中是否可用
控制 cookie 的携带
控制重定向
请求取消
自定义 referrer
API 风格EventPromise
活跃度停止更新不断更新

基于 MIT 许可发布