Skip to content

Fetch

[TOC]

索引

Fetch

方法

  • window.fetch()(url, options?),用于发起网络请求的现代 API,基于 Promise 设计,取代了传统的 XMLHttpRequest。

Response

属性

方法

Fetch

方法

fetch()@

window.fetch()(url, options?),用于发起网络请求的现代 API,基于 Promise 设计,取代了传统的 XMLHttpRequest。

  • urlstring | Request,指定请求的目标 URL 或预配置的 Request 实例。

  • options?{},配置请求的选项对象(如请求方法、请求头、请求体等)。

    • method?GET|POST|PUT|DELETE|PATCH默认:GET,HTTP请求方法。
    • headers?object | Headers请求头信息
    • body?string|Blob|FormData,请求体数据(GET 或 HEAD 请求不能包含 body)。
    • mode?cors|no-cors|same-origin默认:cors,请求模式
    • credentials?omit|same-origin|include默认:same-origin,是否发送凭据(cookie)。
      • omit:不发送。
      • same-origin:同源发送。
      • include:始终发送。
    • cache?default|no-store|no-cache|reload|...,缓存策略。
    • redirect?follow|error|manual,重定向处理方式。
      • follow:自动跟随
      • error:报错
      • manual:手动处理
    • signal?AbortSignal,用于取消请求的 AbortSignal 对象(结合 AbortController 使用)。
  • 返回:

  • resultResponse,Promise 对象,解析为 Response 对象。

    • 常见属性:
    • status:HTTP 状态码(如 200, 404)。
    • statusText:状态描述(如 OK, Not Found)。
    • headers:响应头信息(可通过 headers.get('Content-Type') 获取)。
    • ok:布尔值,表示状态码是否在 200-299 范围内。
    • 常见方法:
    • json():解析响应体为 JSON 对象。
    • text():解析响应体为字符串。
    • blob():解析响应体为 Blob 对象。
    • formData():解析响应体为 FormData 对象。
    • arrayBuffer():解析响应体为 ArrayBuffer 对象。
  • 特性:

    1. 错误处理

      • HTTP 错误状态码fetch 不会因 HTTP 错误状态码(如 404, 500)而拒绝 Promise,需手动检查 response.ok
      js
      fetch(url)
        .then(response => {
          if (!response.ok) throw new Error(`HTTP 错误:${response.status}`);
          return response.json();
        });
      • 网络错误:如请求无法到达服务器,Promise 会被拒绝。
    2. CORS 限制

      • 跨域请求需服务器设置 Access-Control-Allow-Origin 响应头。
      • 非简单请求(如 POST 带非标准头)会触发预检请求(Preflight)。
    3. 兼容性:所有现代浏览器均支持 fetch,但旧版浏览器(如 IE)需使用 Polyfill(如 whatwg-fetch)。

  • 示例:

    1. 基本使用-GET

      js
      // 字符串形式
      fetch('https://api.example.com/data');
      
      // Request 对象形式
      const request = new Request('https://api.example.com/data', { method: 'GET' });
      fetch(request);
    2. 基本使用-POST

      js
      fetch('https://api.example.com/data', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer xyz'
        },
        body: JSON.stringify({ key: 'value' }),
        credentials: 'include',
        mode: 'cors'
      });
    3. 链式处理示例

      js
      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));
    4. 完整示例:考虑各种边界判断

      js
      async function fetchData(url) {
        try {
          const response = await fetch(url, {
            method: 'GET',
            headers: { 'Accept': 'application/json' },
            credentials: 'include'
          });
      
          if (!response.ok) throw new Error(`HTTP 错误:${response.status}`);
          const data = await response.json();
          console.log(data);
        } catch (error) {
          console.error('请求失败:', error);
        }
      }
      
      fetchData('https://api.example.com/data');
    5. 取消请求:使用 AbortController 中止正在进行的请求

      js
      const controller = new AbortController();
      const signal = controller.signal;
      
      fetch('https://api.example.com/data', { signal })
        .then(response => response.json())
        .catch(error => {
          if (error.name === 'AbortError') console.log('请求已取消');
        });
      
      // 取消请求
      controller.abort();
    6. 上传文件:通过 FormData 发送文件。

      js
      const formData = new FormData();
      formData.append('file', fileInput.files[0]);
      
      fetch('https://api.example.com/upload', {
        method: 'POST',
        body: formData
      });
    7. 处理流数据:逐步读取大文件或流。

      readableStream.getReader()(options?)创建一个读取器并将流锁定于其上。一旦流被锁定,其他读取器将不能读取它,直到它被释放。

      js
      fetch('https://api.example.com/large-file')
        .then(response => {
          const reader = response.body.getReader();
          return new ReadableStream({
            start(controller) {
              function push() {
                reader.read().then(({ done, value }) => {
                  if (done) {
                    controller.close();
                    return;
                  }
                  controller.enqueue(value);
                  push();
                });
              }
              push();
            }
          });
        })
        .then(stream => new Response(stream))
        .then(response => response.text())
        .then(text => console.log(text));

Response

属性

ok@【

response.ok

  • :``,

  • :``,

  • :``,

  • 返回:

  • :``,

基本示例

  1. ****:

    js

核心特性

  1. ****:

    js
  2. ****:

    js
  3. ****:

    js

进阶示例

  1. ****:

    js
  2. ****:

    js
  3. ****:

    js

status【

response.status

  • :``,

  • :``,

  • :``,

  • 返回:

  • :``,

基本示例

  1. ****:

    js

核心特性

  1. ****:

    js
  2. ****:

    js
  3. ****:

    js

进阶示例

  1. ****:

    js
  2. ****:

    js
  3. ****:

    js

statusText【

response.statusText

  • :``,

  • :``,

  • :``,

  • 返回:

  • :``,

基本示例

  1. ****:

    js

核心特性

  1. ****:

    js
  2. ****:

    js
  3. ****:

    js

进阶示例

  1. ****:

    js
  2. ****:

    js
  3. ****:

    js

headers@【

response.headers

  • :``,

  • :``,

  • :``,

  • 返回:

  • :``,

基本示例

  1. ****:

    js

核心特性

  1. ****:

    js
  2. ****:

    js
  3. ****:

    js

进阶示例

  1. ****:

    js
  2. ****:

    js
  3. ****:

    js

body@【

response.body

  • :``,

  • :``,

  • :``,

  • 返回:

  • :``,

基本示例

  1. ****:

    js

核心特性

  1. ****:

    js
  2. ****:

    js
  3. ****:

    js

进阶示例

  1. ****:

    js
  2. ****:

    js
  3. ****:

    js

方法

json()@【

response.json()()

  • :``,

  • :``,

  • :``,

  • 返回:

  • :``,

基本示例

  1. ****:

    js

核心特性

  1. ****:

    js
  2. ****:

    js
  3. ****:

    js

进阶示例

  1. ****:

    js
  2. ****:

    js
  3. ****:

    js

text()【

response.text()()

  • :``,

  • :``,

  • :``,

  • 返回:

  • :``,

基本示例

  1. ****:

    js

核心特性

  1. ****:

    js
  2. ****:

    js
  3. ****:

    js

进阶示例

  1. ****:

    js
  2. ****:

    js
  3. ****:

    js

blob()【

response.blob()()

  • :``,

  • :``,

  • :``,

  • 返回:

  • :``,

基本示例

  1. ****:

    js

核心特性

  1. ****:

    js
  2. ****:

    js
  3. ****:

    js

进阶示例

  1. ****:

    js
  2. ****:

    js
  3. ****:

    js

arrayBuffer()【

response.arrayBuffer()()

  • :``,

  • :``,

  • :``,

  • 返回:

  • :``,

基本示例

  1. ****:

    js

核心特性

  1. ****:

    js
  2. ****:

    js
  3. ****:

    js

进阶示例

  1. ****:

    js
  2. ****:

    js
  3. ****:

    js

fromData()【

response.fromData()()

  • :``,

  • :``,

  • :``,

  • 返回:

  • :``,

基本示例

  1. ****:

    js

核心特性

  1. ****:

    js
  2. ****:

    js
  3. ****:

    js

进阶示例

  1. ****:

    js
  2. ****:

    js
  3. ****:

    js