• JavaScript如何拦截全局Fetch的请求和响应


    目前,团队采用了根路径转发的方式,将接口请求转发到服务器上,实现了一定的解耦。然而,随着团队后端策略的变化,现在希望前端直接请求一个新的接口域名,而不再经过中间层的处理。在这种情况下,由于之前的代码中没有对接口请求进行统一的封装,需要考虑如何以最小的成本进行迁移。

    Fetch API简介

    Fetch API是一种用于进行网络请求和响应的现代Web API。它提供了一种简单、强大且灵活的方式来处理HTTP请求。在使用Fetch API时,我们通常创建一个请求对象,然后使用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));
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    总体来说,使用Fetch API发送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));
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    在上面的例子中,我们简单地在拦截函数中输出了请求的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));
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    在这个例子中,我们在拦截函数中输出了响应的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));
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    在上述例子中,我们使用了trycatch块来捕获可能发生的错误,并进行相应的处理。这有助于确保全局Fetch拦截不会导致应用程序的崩溃或不稳定。

  • 相关阅读:
    在Linux中进行K8s部署
    七夕!专属于程序员的浪漫表白
    【OpenPLC学习】RK3568上运行OpenPLC
    Java中使用BigDecimal类相除保留两位小数
    基于matlab实现的卡尔曼滤波匀加速直线运动仿真
    利用百度API进行视频翻译制作
    linux 挂载磁盘 普通用户读写 --chatGPT
    使用rc-danmaku开发弹幕
    blender_mmd_tools_extra 插件介绍
    Ruo-Yi前后端分离的数据过滤
  • 原文地址:https://blog.csdn.net/qq_37834631/article/details/136402796