红宝书第十九讲:详解JavaScript的Fetch API与Ajax请求

资料取自《JavaScript高级程序设计(第5版)》
查看总目录:红宝书学习大纲


一、基本概念:为什么需要Fetch?

Fetch API是浏览器提供的现代网络请求工具,替代传统的Ajax(XMLHttpRequest)。核心特点:

  • 基于Promise → 代码更简洁(告别回调函数嵌套) 12
  • 支持流式处理 → 大文件分块传输时不卡死页面 3
  • 灵活配置请求头/请求方法 → 适配各种API需求 34

示例1:发送最简单的GET请求

// 请求JSON数据并解析
fetch('https://api.example.com/data')
  .then(response => response.json()) // 解析为JSON → 返回新Promise
  .then(data => console.log('获取的数据:', data))
  .catch(error => console.error('请求失败:', error));

1: 资料1指出fetch()唯一必传参数是资源URL
5: 资料5说明Fetch返回Promise并统一处理响应


二、配置请求:POST请求与自定义参数

通过第二个参数传入配置对象,设置方法、请求头、请求体等 34

示例2:发送带JSON数据的POST请求

const userData = { name: '小明', age: 18 };

fetch('https://api.example.com/submit', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json' // 告诉服务器发送的是JSON
  },
  body: JSON.stringify(userData) // 将对象转为JSON字符串
})
  .then(response => response.text())
  .then(text => console.log('服务器响应:', text));

3: 资料3展示如何发送JSON和表单数据
4: 资料4提供Request对象的配置示例


三、处理不同类型响应

Fetch返回的Response对象提供多种解析方法:5

  • .json() → 解析为JSON对象
  • .text() → 解析为纯文本
  • .blob() → 解析为二进制数据(如图片)

示例3:下载并显示图片

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

四、错误处理:网络错误≠HTTP错误

需要两步处理错误

  1. 网络层错误(如断网) → 自动触发.catch()
  2. HTTP错误状态码(如404/500) → 需手动检查响应状态

示例4:完整的错误处理

fetch('https://api.example.com/404-page')
  .then(response => {
    if (!response.ok) { // 检查HTTP状态码是否成功(200-299)
      throw new Error(`HTTP错误! 状态码: ${response.status}`);
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error('错误信息:', error)); // 处理所有错误

5: 资料5强调需手动检查response.ok


五、跨域请求(CORS)的配置

浏览器默认阻止跨域请求,需设置服务端响应头允许,或配置请求的mode14

// 允许跨域请求(需服务器支持)
fetch('https://another-domain.com/data', {
  mode: 'cors', // 默认值,可选 'no-cors'等
  headers: {
    'Authorization': 'Bearer token123' // 认证令牌
  }
});

六、高级用法:上传文件

示例5:通过FormData上传文件

<input type="file" id="fileInput">
const fileInput = document.querySelector('#fileInput');
const formData = new FormData();
formData.append('file', fileInput.files[0]); // 添加文件

fetch('https://api.example.com/upload', {
  method: 'POST',
  body: formData // 自动设置正确的Content-Type
})
  .then(response => response.json())
  .then(result => console.log('上传成功:', result));

3: 资料3演示使用FormData发送文件


对比传统Ajax(XMLHttpRequest)

为什么推荐Fetch? 2

  1. 代码更简洁 → 无需监听多个事件(onload/onerror
  2. Promise链式调用 → 更易维护
  3. 自动处理编码 → 如直接解析JSON、Blob

目录:总目录

上篇文章:红宝书第十八讲:详解JavaScript的async/await与错误处理

脚注


  1. 《JavaScript高级程序设计(第5版)》中说明fetch基本用法与请求初始化
  2. 《JavaScript高级程序设计(第5版)》对比XHR与Fetch的优缺点
  3. 《JavaScript高级程序设计(第5版)》提供发送表单数据与文件的实例
  4. 《JavaScript高级程序设计(第5版)》展示Request对象的详细配置
  5. 《JavaScript高级程序设计(第5版)》强调需手动检查响应状态码和错误处理

kovli
10 声望4 粉丝