JavaScript如何拦截全局Fetch的请求与响应详解

作者:木棉

时间:2026-10-31

浏览:631

本文详解如何在JavaScript中通过重写window.fetch实现全局请求与响应拦截。涵盖GET/POST基础用法、身份验证、日志记录及错误处理机制,对比Fetch与XHR差异,帮助前端团队以最小成本完成接口迁移与统一封装。

文章目录

前言

当前团队采用根路径转发机制,将接口请求代理至服务器以达成解耦。鉴于后端策略调整,前端需直连新域名接口并绕过中间层。因既往代码缺乏统一封装,需以最低成本完成迁移。

Fetch API简介

Fetch API是现代Web网络请求与响应接口,提供简洁、强大且灵活的处理方式。使用时通常构建请求对象,通过fetch函数发送请求,并处理返回的Promise。

// GET请求示例:
fetch('https://your.api.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

// POST请求示例:
fetch('https://your.api.com/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ id: 123, name: 'admin' }),
})
  .then(response => response.json())
  .then(data => console.log('POST Request:', data))
  .catch(error => console.error('POST Request Error:', error));

总体而言,GET与POST请求发送方式基本一致,但POST需额外处理请求方法及请求体数据。

注意:鉴于GET请求代码极简,有时为图方便直接使用fetch。这给后续请求、响应及错误处理带来不便。若大面积修改代码,既耗时又需测试。

全局Fetch拦截的需求

有时需在全应用范围内拦截处理所有Fetch请求与响应,旨在添加全局身份验证、记录日志或处理错误。为此,可使用window.fetch拦截全局Fetch。

拦截请求

拦截全局Fetch请求,可重写window.fetch方法。在此方法中添加自定义逻辑后调用原始fetch方法。示例如下:

const originalFetch = window.fetch;

window.fetch = function(url, options) {
  // 添加你的自定义逻辑
  console.log('Intercepted request to:', url);

  // 调用原始的fetch方法
  return originalFetch(url, options);
};

// 使用拦截后的fetch
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

上述示例在拦截函数中输出请求URL,最后调用原始fetch方法。由此可在每个全局Fetch请求前执行自定义逻辑。

拦截响应

同理,也可拦截全局Fetch响应。此举允许在处理响应前添加通用逻辑,如检查状态码或处理错误。

const originalFetch = window.fetch;

window.fetch = function(url, options) {
  // 调用原始的fetch方法
  return originalFetch(url, options)
    .then(response => {
      // 添加你的自定义响应逻辑
      console.log('Intercepted response from:', url);

      // 返回原始的响应
      return response;
    });
};

// 使用拦截后的fetch
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

此例在拦截函数中输出响应URL,最后返回原始响应。从而允许在处理全局Fetch响应前执行自定义逻辑。

处理错误

实际应用中需考虑错误处理。若拦截过程出错,应适当处理,避免对应用其他部分产生负面影响。

const originalFetch = window.fetch;

window.fetch = function(url, options) {
  try {
    // 添加你的自定义请求逻辑
    console.log('Intercepted request to:', url);

    // 调用原始的fetch方法
    return originalFetch(url, options)
      .then(response => {
        // 添加你的自定义响应逻辑
        console.log('Intercepted response from:', url);

        // 返回原始的响应
        return response;
      })
      .catch(error => {
        // 处理全局Fetch响应错误
        console.error('Intercepted response error:', error);
        throw error;
      });
  } catch (error) {
    // 处理全局Fetch请求错误
    console.error('Intercepted request error:', error);
    return Promise.reject(error);
  }
};

// 使用拦截后的fetch
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

上述示例使用try和catch块捕获可能错误并处理。这有助于确保全局Fetch拦截不导致应用崩溃或不稳定。

附:fetch/xhr和其他请求的区别

fetch/xhr与其他请求(如axios、ajax等)的主要区别在于使用方式及功能差异。

首先,fetch是基于Promise的现代化网络请求API,xhr是传统XMLHttpRequest对象。fetch基于新Web标准,能更好处理请求响应并支持更多现代功能,而xhr属老旧方式。

另一区别在于fetch API返回Promise对象,可使用链式调用及async/await语法,处理异步操作十分便捷。而xhr需使用回调函数处理异步操作,代码结构相对复杂。

此外,fetch API默认不携带cookie,需设置credentials属性为"include"方可发送cookie。而xhr默认发送cookie,需手动设置xhr.withCredentials属性为true来禁止发送。

另外,fetch API默认仅拒绝请求错误状态码(如404或500等),不拒绝其他网络错误(如网络超时)。这意味着需手动检查并处理网络错误。而xhr可通过onerror事件处理所有类型网络错误。

最后,fetch API使用相对简单,语法更直观。而xhr相对复杂,需手动设置请求头、处理请求和响应等。

总结而言,fetch/xhr与其他请求的主要区别在于使用方式、功能支持和代码结构等方面。fetch提供更现代化、简洁的API,支持Promise和async/await语法,但xhr仍是可靠且广泛使用的老旧方式。

总结

至此,关于JavaScript如何拦截全局Fetch的请求与响应的文章介绍完毕。更多相关js拦截全局Fetch请求和响应内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章