fetch用法

甜岛和星

Fetch API 的用法指南

引言

Fetch API 是现代 Web 开发中用于发起 HTTP 请求的一种接口。它提供了一个全局的 fetch() 方法,可以替代传统的 XMLHttpRequest 来执行异步网络请求,并且基于 Promise 设计,使得异步操作更加简洁和易于管理。

Fetch API 的基本用法

fetch() 方法的基本语法如下:

fetch(url, options)
  .then(response => {
    // 处理响应
  })
  .catch(error => {
    // 处理错误
  });
  • url 是请求的目标资源地址。
  • options 是一个可选参数,可以指定请求的方法、头部信息、请求体等。

发起 GET 请求

发起一个简单的 GET 请求非常简单:

fetch('https://api.example.com/data')
  .then(response => response.json()) // 解析 JSON 响应体
  .then(data => {
    console.log(data); // 处理获取的数据
  })
  .catch(error => {
    console.error('请求失败:', error);
  });

发起 POST 请求

发起 POST 请求需要在 options 中指定方法和请求体:

fetch('https://api.example.com/submit', {
  method: 'POST', // 指定请求方法
  headers: {
    'Content-Type': 'application/json' // 设置请求头部
  },
  body: JSON.stringify({
    key1: 'value1',
    key2: 'value2'
  }) // 发送 JSON 格式的请求体
})
.then(response => response.json())
.then(data => {
  console.log(data); // 处理返回的数据
})
.catch(error => {
  console.error('请求失败:', error);
});

自定义请求头部

有时,你可能需要在请求中包含自定义头部,例如认证令牌:

fetch('https://api.example.com/secure-data', {
  method: 'GET',
  headers: {
    'Authorization': 'Bearer your_token_here'
  }
})
.then(response => response.json())
.then(data => {
  console.log(data);
})
.catch(error => {
  console.error('请求失败:', error);
});

处理响应状态

fetch() 方法返回的 Promise 会解析为一个 Response 对象,你可以通过检查这个对象的状态码来确定请求是否成功:

fetch('https://api.example.com/data')
  .then(response => {
    if (response.ok) {
      return response.json();
    }
    throw new Error('网络响应错误');
  })
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error('请求失败:', error);
  });

并发请求

Fetch API 支持并发请求,你可以使用 Promise.all() 来并行处理多个请求:

Promise.all([
  fetch('https://api.example.com/data1'),
  fetch('https://api.example.com/data2')
])
.then(responses => Promise.all(responses.map(response => response.json())))
.then(data => {
  console.log(data[0], data[1]); // 处理并发请求返回的数据
})
.catch(error => {
  console.error('请求失败:', error);
});

取消 Fetch 请求

Fetch API 本身不支持取消请求,但可以通过封装 fetch 函数来实现取消功能:

const abortableFetch = (url, options, controller) => {
  return fetch(url, {
    ...options,
    signal: controller.signal
  });
};

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

// 某个条件下取消请求
setTimeout(() => controller.abort(), 1000);

abortableFetch('https://api.example.com/data', {}, controller)
  .then(response => response.json())
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    if (error.name === 'AbortError') {
      console.log('请求被取消');
    } else {
      console.error('请求失败:', error);
    }
  });

结语

Fetch API 为 Web 开发者提供了一个强大且灵活的接口来处理网络请求。它基于 Promise,使得异步代码更加简洁和易于管理。通过合理使用 Fetch API,可以提高 Web 应用的性能和用户体验。然而,开发者在使用时需要注意其不支持同步操作、请求取消等限制,并采取相应的措施来解决这些问题。

版权声明:本页面内容旨在传播知识,为用户自行发布,若有侵权等问题请及时与本网联系,我们将第一时间处理。E-mail:284563525@qq.com

目录[+]

取消
微信二维码
微信二维码
支付宝二维码