历史搜索

Fetch API 入门

游客2024-06-23 09:30:01

Fetch 是一种较新的、基于承诺的 API,它允许我们执行 Ajax 请求,而无需处理与XMLHttpRequest相关的所有麻烦。正如您将在本文中看到的,Fetch 非常易于使用和操作,并且大大简化了从 API 获取资源的过程。此外,它现在已在所有现代浏览器中得到支持,因此使用 Fetch 真的是一件轻而易举的事。

获取请求

让我们演示一个简单的 GET 请求,得到我们自己从JSONPlaceholder API中获取了一些虚拟数据

fetch('https://jsonplaceholder.typicode.com/users')
  .then(res => res.json())
  .then(res => res.map(user => user.username))
  .then(userNames => console.log(userNames));
输输出将是如下的用户名数组:

["Bret", "Antonette", "Samantha", "Karianne", "Kamren", "Leopoldo_Corkery", "Elwyn.Skiles", "Maxime_Nienow", "Delphine", "Moriah.Stanton"]

鉴于我们期望 JSON 响应,我们首先需要调用json()方法来转换回复对象变成我们可以与之交互的对象。text()如果我们期望 XML 响应,则可以使用它

发布、放置和删除请求

要发出除GET之外的请求,请将对象作为第二个参数传递给 fetch 调用,其中包含要使用的方法以及任何所需的标头和请求正文:

const myPost = {
  title: 'A post about true facts',
  body: '42',
  userId: 2
}

const options = {
  method: 'POST',
  body: JSON.stringify(myPost),
  headers: {
    'Content-Type': 'application/json'
  }
};

fetch('https://jsonplaceholder.typicode.com/posts', options)
  .then(res => res.json())
  .then(res => console.log(res));

JSONPlaceholder将附加 ID 的 POST 数据发回给我们:

Object {
  body: 42,
  id: 101,
  title: "A post about true facts",
  userId: 2
}

错误处理

使用 Fetch API 进行错误处理时有一个问题(双关语