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 请求的首选方式。

相关推荐
曦樂~4 小时前
【Web Development】02 CSS
前端·css
风骏时光牛马4 小时前
后端服务接口开发与数据逻辑处理
前端
东鹏特饮4 小时前
经典打砖块(Breakout)游戏
前端·css·css3
IT_陈寒4 小时前
Vite的HMR把我整不会了:一个生产环境的热更新坑
前端·人工智能·后端
Mh5 小时前
如何使用双缓冲优化视频切换
前端
risenav5 小时前
低头蓄力,抬头起跳:《萤虫跳跳》的 Rokid AIUI 开发实战
前端
ZhengEnCi5 小时前
如何看待 Fable 5.2 用纯代码生成 1.4MB 视觉作品:光追、水面、倒影、火光的程序化生成原理
前端
再吃一根胡萝卜6 小时前
DSH 插件的 Host 与 Client:为什么「只加载了 Host」,以及要不要自己写 Client 加载器
前端
parade岁月6 小时前
AI 写的前端代码为什么总像 5 年前的?Chrome 官方出手了
前端
tryCbest7 小时前
Vue系列——第 15 篇:内置组件全家桶——Transition、Teleport、Suspense、KeepAlive
前端·vue.js