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

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

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