Fetch API

2024-07-30 07:22:08 224
Fetch API 提供了一种 JavaScript 接口,用于在浏览器中执行 HTTP 请求。它基于 Promises,使其比旧的 XMLHttpRequest 更加灵活和易用。

基本用法

Fetch API 的基本用法非常简单,通过调用 fetch 方法并传入请求的 URL,即可返回一个 Promise。

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

发送请求

GET 请求

GET 请求是 Fetch API 的默认请求类型,只需传入请求 URL。

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

POST 请求

POST 请求需要使用配置对象,并指定请求方法和请求体。

fetch('https://api.example.com/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'John',
    age: 30
  })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

配置选项

Fetch API 的配置选项非常灵活,可以设置请求方法、头信息、请求体、模式等。

fetch('https://api.example.com/data', {
  method: 'PUT', // 请求方法:GET, POST, PUT, DELETE 等
  headers: {
    'Content-Type': 'application/json', // 请求头信息
    'Authorization': 'Bearer token'
  },
  body: JSON.stringify({ // 请求体
    name: 'Jane',
    age: 25
  }),
  mode: 'cors', // 请求模式:cors, no-cors, same-origin
  cache: 'no-cache' // 缓存模式:default, no-cache, reload, force-cache, only-if-cached
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

处理响应

Fetch API 返回的 Promise 解析为一个 Response 对象。可以使用 json()text() 等方法来解析响应体。

fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok ' + response.statusText);
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

错误处理

可以使用 .catch() 方法来捕获和处理请求中的错误。

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));