JS — fetch详解

Fetch API 是一组用于在 Web 浏览器中进行网络请求的现代 JavaScript API。它提供了一种更简洁、更强大的方式来处理网络请求,相比传统的 XMLHttpRequest 对象,Fetch API 更易于使用且功能更丰富。

1.Fetch的特点:

  • 基于 Promise:Fetch API 是基于 Promise 的,这意味着你可以使用 Promise 的链式方法来处理异步操作,使代码更清晰易懂。
  • 简洁的 API:Fetch API 提供了一组简洁的方法来执行各种类型的 HTTP 请求,包括 GET、POST、PUT、DELETE 等。
  • 支持流式数据:Fetch API 支持读取和写入流式数据,这使得处理大型响应或请求时更加高效。
  • 支持跨域请求:Fetch API 默认支持跨域请求,但在某些情况下可能需要额外配置以处理 CORS(跨域资源共享)。

2.Fetch的基础使用:

fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json(); // 将响应解析为 JSON 格式
  })
  .then(data => {
    // 处理返回的数据
    console.log(data);
  })
  .catch(error => {
    // 处理错误
    console.error('There was a problem with the fetch operation:', error);
  });

//fetch() 函数发送了一个 GET 请求到指定的 URL,并返回一个 Promise 对象。使用 .then() 方法处理响应,并将其解析为 JSON 格式。如果请求失败或者响应状态码不在 200-299 范围内,将会抛出一个错误并通过 .catch() 方法捕获和处理。

3.自定义请求头:

//Fetch API 允许你自定义请求头,以便在请求中包含所需的信息。你可以通过传递一个对象作为第二个参数来设置请求的配置,其中包括 headers 属性来定义请求头。
const headers = new Headers();
headers.append('Content-Type', 'application/json');

fetch('https://api.example.com/data', {
  method: 'POST',
  headers: headers,
  body: JSON.stringify({ username: 'example', password: '123456' })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));


//我们创建了一个包含自定义请求头的 Headers 对象,并在请求中传递了这个对象,以便服务器能够正确解析请求。

4.支持 FormData:

//Fetch API 支持使用 FormData 对象来处理表单数据。你可以将 FormData 对象传递给 fetch() 函数的 body 参数,从而方便地发送表单数据。

const formData = new FormData();
formData.append('username', 'example');
formData.append('password', '123456');

fetch('https://api.example.com/login', {
  method: 'POST',
  body: formData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

//我们创建了一个 FormData 对象,并向其添加了表单字段。然后将该对象作为请求的 body 参数传递给 fetch() 函数。

5.可中断请求:

//使用 AbortController 和 AbortSignal,可以在需要时中断 Fetch 请求。这对于需要取消或中止某些操作的情况非常有用。

const controller = new AbortController();
const signal = controller.signal;

setTimeout(() => controller.abort(), 5000); // 5秒后中断请求

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

//我们创建了一个 AbortController,并在 5 秒后调用了 abort() 方法来中断请求。

6.不支持同步请求:

//Fetch API 不支持同步请求,因为它是基于 Promise 的。这意味着你不能像使用 XMLHttpRequest 那样直接在代码中执行同步请求。

7.支持缓存:

//Fetch API 支持使用缓存来提高性能。你可以通过设置请求的 cache 属性来控制缓存策略。
fetch('https://api.example.com/data', {
  method: 'GET',
  cache: 'no-store' // 禁用缓存
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

//我们通过设置 cache 属性为 'no-store' 来禁用缓存。

8.跨平台支持:

//Fetch API 在现代的 Web 浏览器中得到了广泛支持,包括 Chrome、Firefox、Safari 等。此外,它也可以在 Node.js 环境中使用,但需要使用第三方库来模拟浏览器环境。
posted on 2024-05-13 09:42  萬事順意  阅读(355)  评论(0编辑  收藏  举报