你说的 Fetch 具体是指哪一种呢?因为“Fetch”在不同的技术语境中有不同的用法:

  1. 前端开发(JavaScript)中的 Fetch API
    • 这是浏览器内置的接口,用于进行网络请求(代替传统的 XMLHttpRequest)。
    • 常用来发送 HTTP 请求(GET、POST、PUT、DELETE 等)。
    示例:GET 请求fetch('https://api.example.com/data') .then(response => { if (!response.ok) { throw new Error('网络错误: ' + response.status); } return response.json(); }) .then(data => { console.log(data); }) .catch(error => { console.error('请求失败:', error); }); 示例:POST 请求fetch('https://api.example.com/submit', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: '阿杰', age: 25 }) }) .then(res => res.json()) .then(data => console.log(data)) .catch(err => console.error(err)); 👉 优点:基于 Promise,语法简洁,可配合 async/await 使用。async function getData() { try { const res = await fetch('https://api.example.com/data'); const data = await res.json(); console.log(data); } catch (error) { console.error('错误:', error); } }

  1. Git 中的 fetch 命令
    • git fetch:从远程仓库获取最新分支、提交记录,但不会自动合并到本地分支。
    • 常见用法:git fetch origin git fetch origin main
    • 区别:
      • git fetch 只下载,不修改当前工作区。
      • git pull = git fetch + git merge

  1. 数据库 / 大数据(比如 Flink、Spark、JDBC)里的 Fetch
    • 一般表示从结果集中获取数据,比如:
      • JDBC 的 ResultSet.fetchSize 表示每次取多少条数据。
      • Flink 的 connector 也有 fetch-size 参数来控制批量读取。

好的阿杰 👍
我来给你写一个 超详细的 Fetch API 使用教程(前端开发中最常用的那个),涵盖基础、进阶和常见问题。


🔹 Fetch API 使用详解

1. 什么是 Fetch?

  • fetch() 是浏览器内置的 HTTP 请求函数,基于 Promise
  • 主要用来替代老的 XMLHttpRequest (XHR),语法更简洁。

基本语法:

fetch(url, options)
  .then(response => {
    // response 是一个 Response 对象
  })
  .catch(error => {
    // 网络错误(如断网、跨域)
  });


2. GET 请求

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => {
    if (!response.ok) {
      throw new Error('请求失败:' + response.status);
    }
    return response.json(); // 解析为 JSON
  })
  .then(data => console.log(data))
  .catch(error => console.error(error));

👉 response.ok 表示状态码 200-299。
👉 response.json() 会返回一个 Promise,需要再 .then() 处理。


3. POST 请求

fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    title: '阿杰的测试',
    body: '这是一个用 Fetch 发送的请求',
    userId: 1
  })
})
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));

👉 headers 用来指定请求头,常见的有:

  • Content-Type: application/json
  • Authorization: Bearer token

4. PUT & DELETE

修改数据(PUT)

fetch('https://jsonplaceholder.typicode.com/posts/1', {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    title: '更新后的标题',
    body: '内容已更新',
    userId: 1
  })
})
.then(res => res.json())
.then(data => console.log(data));

删除数据(DELETE)

fetch('https://jsonplaceholder.typicode.com/posts/1', {
  method: 'DELETE'
})
.then(res => {
  if (res.ok) {
    console.log('删除成功');
  }
});


5. 配合 async/await

更简洁的写法:

async function getData() {
  try {
    const res = await fetch('https://jsonplaceholder.typicode.com/posts/1');
    if (!res.ok) throw new Error('请求失败');
    const data = await res.json();
    console.log(data);
  } catch (err) {
    console.error(err);
  }
}
getData();


6. 处理不同返回类型

  • JSONresponse.json()
  • 文本response.text()
  • 二进制文件response.blob()
  • 数组缓冲区response.arrayBuffer()

例子(下载图片):

fetch('https://example.com/image.png')
  .then(res => res.blob())
  .then(blob => {
    const img = document.createElement('img');
    img.src = URL.createObjectURL(blob);
    document.body.appendChild(img);
  });


7. 常见问题 ⚠️

  1. fetch 不会抛出 HTTP 错误
    • 例如 404/500 不会进入 catch,只会进入 .then()
    • 需要手动检查 response.ok
  2. 跨域问题 (CORS)
    • 如果后端没设置允许跨域(Access-Control-Allow-Origin),fetch 会报错。
  3. 超时问题
    • fetch 没有内置超时,需要自己用 AbortController
    const controller = new AbortController(); const timeout = setTimeout(() => controller.abort(), 5000); fetch('https://jsonplaceholder.typicode.com/posts', { signal: controller.signal }) .then(res => res.json()) .then(data => console.log(data)) .catch(err => console.error('请求超时或失败', err));

✅ 总结:

  • fetch() 是前端发 HTTP 请求的首选方式。
  • GET/POST/PUT/DELETE 都能用。
  • 搭配 async/await 更简洁。
  • 注意 response.ok 和跨域问题。