Fetch API 详解

Fetch API 详解

Fetch API 是现代 JavaScript 中用于发起网络请求的标准 API,它比传统的 XMLHttpRequest 更强大、更灵活,且基于 Promise 实现。

基本语法

javascript 复制代码
fetch(resource [, init])
  .then(response => {
    // 处理响应
  })
  .catch(error => {
    // 处理错误
  });

参数说明

  1. resource: 请求的资源路径(URL)

  2. init (可选): 配置对象,可以包含以下属性:

    • method: 请求方法(GET, POST, PUT, DELETE等)
    • headers: 请求头信息
    • body: 请求体数据
    • mode: 请求模式(cors, no-cors, same-origin)
    • credentials: 是否发送 cookies(include, same-origin, omit)
    • cache: 缓存模式
    • redirect: 重定向处理方式
    • referrer: 引用来源
    • signal: AbortSignal 用于取消请求

常见请求示例

1. GET 请求

javascript 复制代码
fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error('网络响应不正常');
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error('请求失败:', error));

2. POST 请求

javascript 复制代码
fetch('https://api.example.com/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer token'
  },
  body: JSON.stringify({
    name: 'John',
    age: 30
  })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

3. 上传文件

javascript 复制代码
const formData = new FormData();
formData.append('file', fileInput.files[0]);

fetch('https://api.example.com/upload', {
  method: 'POST',
  body: formData
})
.then(response => response.json())
.then(result => console.log('上传成功:', result))
.catch(error => console.error('上传失败:', error));

响应处理

Fetch API 返回的 Response 对象包含以下常用属性和方法:

属性

  • ok: 布尔值,表示请求是否成功(状态码 200-299)
  • status: HTTP 状态码
  • statusText: 状态文本
  • headers: 响应头信息
  • url: 请求的 URL

方法

  • json(): 解析响应体为 JSON
  • text(): 获取响应体文本
  • blob(): 获取响应体为 Blob 对象
  • formData(): 获取响应体为 FormData 对象
  • arrayBuffer(): 获取响应体为 ArrayBuffer

错误处理

Fetch API 的错误处理需要注意:

  1. 网络错误(如无法连接)会触发 catch
  2. HTTP 错误状态(如 404, 500)不会触发 catch,需要检查 response.ok
javascript 复制代码
fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error('请求出现问题:', error));

高级用法

1. 设置超时

javascript 复制代码
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000);

fetch('https://api.example.com/data', {
  signal: controller.signal
})
.then(response => {
  clearTimeout(timeoutId);
  return response.json();
})
.catch(error => {
  if (error.name === 'AbortError') {
    console.log('请求超时');
  } else {
    console.error('其他错误:', error);
  }
});

2. 并发请求

javascript 复制代码
Promise.all([
  fetch('https://api.example.com/data1'),
  fetch('https://api.example.com/data2')
])
.then(responses => Promise.all(responses.map(res => res.json())))
.then(data => {
  console.log('数据1:', data[0]);
  console.log('数据2:', data[1]);
})
.catch(error => console.error('请求失败:', error));

3. 自定义请求拦截

javascript 复制代码
// 请求拦截器
const originalFetch = window.fetch;
window.fetch = async (...args) => {
  console.log('发起请求:', args[0]);
  // 可以在这里添加认证token等
  const response = await originalFetch(...args);
  console.log('收到响应:', response);
  return response;
};

注意事项

  1. Fetch 默认不会发送或接收 cookies,需要设置 credentials: 'include'
  2. 错误状态码(如 404, 500)不会触发 catch,需要检查 response.ok
  3. Fetch 不支持直接监控上传/下载进度(可以使用 XMLHttpRequest 替代)
  4. 在 Node.js 环境中,需要使用 node-fetch 或类似 polyfill

Fetch API 提供了强大而灵活的网络请求能力,是现代 Web 开发中处理 HTTP 请求的首选方式。

相关推荐
惜.己几秒前
针对nvm不能导致npm和node生效的解决办法
前端·npm·node.js
F2E_Zhangmo29 分钟前
基于cornerstone3D的dicom影像浏览器 第二章 加载本地文件夹中的dicom文件并归档
前端·javascript·css
用户21411832636021 小时前
Nano Banana免费方案来了!Docker 一键部署 + 魔搭即开即用,小白也能玩转 AI 图像编辑
前端
Zacks_xdc1 小时前
【前端】使用Vercel部署前端项目,api转发到后端服务器
运维·服务器·前端·安全·react.js
给月亮点灯|1 小时前
Vue基础知识-脚手架开发-使用Axios发送异步请求+代理服务器解决前后端分离项目的跨域问题
前端·javascript·vue.js
张迅之2 小时前
【React】Ant Design 5.x 实现tabs圆角及反圆角效果
前端·react.js·ant-design
蔗理苦3 小时前
2025-09-05 CSS3——盒子模型
前端·css·css3
二川bro4 小时前
第25节:VR基础与WebXR API入门
前端·3d·vr·threejs
上单带刀不带妹4 小时前
Node.js 的模块化规范是什么?CommonJS 和 ES6 模块有什么区别?
前端·node.js·es6·模块化
缘如风4 小时前
easyui 获取自定义的属性
前端·javascript·easyui