Fetch 是用于发送和接收网络请求的 API,它为 JavaScript 提供了一种现代、简单和强大的方式来处理网络请求。

以下是使用 Fetch 的一些基本用法:

  1. 发送 GET 请求
fetch('https://example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  1. 发送 POST 请求
fetch('https://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))
  1. 处理错误
fetch('https://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('Error:', error));

在使用 Fetch 时,请记住:

  • fetch 返回一个 promise,你可以使用 then() 和 catch() 方法来处理响应和错误。
  • 需要设置请求的方法、头部和主体。默认是使用 GET 请求。
  • 数据格式需要处理,例如,使用 JSON.stringify() 将 JavaScript 对象转换为 JSON 字符串,使用 response.json() 将响应体转换为 JavaScript 对象。
  • 处理错误是非常重要的。在响应不是 200 时,需要抛出错误并在 catch() 中处理。
Fetch API 使用指南:发送网络请求的现代方式

原文地址: https://www.cveoy.top/t/topic/l4dc 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录