Fetch API 的基本使用

Fetch API

Fetch API 是用于从服务器获取资源的 Web API。它提供了一种更高级别的接口,可以用来获取资源,而无需使用 XMLHttpRequest。

Fetch API 基于 Promises,这意味着它返回一个 Promise 对象,可以用于异步处理。

Fetch API 允许你指定请求的 HTTP 方法、URL、请求头、请求体等。

Fetch API 还提供了请求和响应的接口,允许你读取响应头、状态码、内容等。

Fetch API 还提供了超时设置、重试设置、缓存设置等功能。

基本用法

Fetch API 的基本用法如下:

fetch(url)
  .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('Fetch failed:', error);
   });
  1. 调用 fetch() 方法,传入请求 URL。
  2. fetch() 方法返回一个 Promise 对象,该对象会在响应到达时被 resolve。
  3. then() 方法中,我们可以处理响应。如果响应状态码不是 2xx,我们可以抛出一个错误。
  4. 如果响应状态码是 2xx,我们可以调用 json() 方法,解析响应内容并返回一个 Promise 对象。
  5. then() 方法中,我们可以处理解析后的响应数据。
  6. 如果 fetch() 方法抛出错误,我们可以在 catch() 方法中处理。

进阶用法

Fetch API 还有一些高级用法,包括:

  • 请求超时设置:fetch(url, { timeout: 5000 }),设置超时时间为 5 秒。
  • 请求重试设置:fetch(url, { retries: 3 }),设置最大重试次数为 3 次。
  • 请求缓存设置:fetch(url, { cache: 'default' }),使用默认缓存。
  • 请求头设置:fetch(url, { headers: { 'Content-Type': 'application/json' } }),设置请求头。
  • 请求体设置:fetch(url, { method: 'POST', body: JSON.stringify(data) }),设置请求体。
  • 响应状态码检查:response.ok,检查响应状态码是否为 2xx。
  • 响应头读取:response.headers.get('Content-Type'),读取响应头。
  • 响应内容读取:response.text()response.json()response.blob()response.formData(),读取响应内容。
  • 请求取消:const controller = new AbortController(); fetch(url, { signal: controller.signal }),取消请求。

封装 fetch

为了方便使用,我们可以封装 fetch,使其更加易用。

function fetchData(url, options = {}) {
  const { method = 'GET', headers = {}, body } = options;
  return fetch(url, { method, headers, body })
    .then(response => {
        if (!response.ok) {
           throw new Error('Network response was not ok');
        }
        return response.json();
     })
    .catch(error => {
        console.error('Fetch failed:', error);
     });
}

// 使用
fetchData('https://example.com/api/data')
  .then(data => {
      console.log(data);
   });

封装后的 fetchData() 方法可以传入 URL 和选项对象,包括请求方法、请求头、请求体等。

fetch 在 Vue 中的封装与使用

在 Vue 中,我们可以使用插件来封装 fetch。

// 安装插件
import Vue from 'vue';
import VueFetch from 'vue-fetch';
Vue.use(VueFetch);


// 使用
this.$http.get('https://example.com/api/data')
  .then(response => {
      console.log(response.data);
   })
  .catch(error => {
      console.error('Fetch failed:', error);
   });

在 Vue 中,我们可以使用 this.$http 对象来调用 fetch。

this.$http 对象封装了 fetch,并提供了一些额外的功能,如:

  • 响应状态码检查:this.$http.get(url).then(response => {... }).catch(error => {... }),检查响应状态码是否为 2xx。
  • 请求超时设置:this.$http.get(url, { timeout: 5000 }).then(response => {... }).catch(error => {... }),设置超时时间为 5 秒。
  • 请求重试设置:this.$http.get(url, { retries: 3 }).then(response => {... }).catch(error => {... }),设置最大重试次数为 3 次。
  • 请求缓存设置:this.$http.get(url, { cache: 'default' }).then(response => {... }).catch(error => {... }),使用默认缓存。
  • 请求头设置:this.$http.get(url, { headers: { 'Content-Type': 'application/json' } }).then(response => {... }).catch(error => {... }),设置请求头。
  • 请求体设置:this.$http.post(url, { data: { name: 'John' } }).then(response => {... }).catch(error => {... }),设置请求体。
  • 响应内容读取:this.$http.get(url).then(response => { console.log(response.data) }).catch(error => {... }),读取响应内容。

参考

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
fetch API 是一种用于进行网络请求的现代化的JavaScript API。它提供了一种更简洁和现代的方式来进行异步请求。以下是使用fetch API基本步骤: 1. 发起一个GET请求: ```javascript fetch(url) .then(response => response.json()) .then(data => { // 处理返回的数据 }) .catch(error => { // 处理错误 }); ``` 在上面的代码中,`url`是你要发送请求的目标URL。fetch函数返回一个Promise对象,可以使用`.then()`方法处理成功的响应,使用`.catch()`方法处理错误。 2. 发起其他类型的请求(POST、PUT、DELETE等): ```javascript fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(response => response.json()) .then(data => { // 处理返回的数据 }) .catch(error => { // 处理错误 }); ``` 在上面的代码中,我们通过在fetch函数的第二个参数中设置`method`、`headers`和`body`来指定请求的类型、头信息和请求体数据。 3. 处理响应数据: fetch API 提供了一种处理不同类型响应数据的方式。常见的方法包括: - `response.json()`:将响应解析为JSON格式的数据。 - `response.text()`:将响应解析为文本。 - `response.blob()`:将响应解析为Blob对象。 - `response.arrayBuffer()`:将响应解析为ArrayBuffer对象。 你可以根据实际需要选择适合的方法来处理响应数据。 请注意,fetch API 默认不会将网络错误(例如404或500错误)视为拒绝的Promise,而是将这些错误视为成功的响应。因此,你需要根据HTTP状态码来检查是否有错误发生。 这是fetch API基本用法示例。你可以根据需要进行更多的定制和配置,例如设置请求头、处理错误等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值