请求拦截 XMLHttpRequest和fetch

Posted 左手121

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了请求拦截 XMLHttpRequest和fetch相关的知识,希望对你有一定的参考价值。

// 拦截请求
const XHR = window.XMLHttpRequest

window.XMLHttpRequest = class XMLHttpRequest extends XHR 
  method = 'GET'

  constructor() 
    super()
    const  open  = this
    this.open = (
      method: string,
      url: string | URL,
      async?: boolean,
      username?: string | null,
      password?: string | null,
    ) => 
      this.method = method || 'GET'
      window.dispatchEvent(
        new CustomEvent('ajax_interceptor_start', 
          detail: 
            methods: this.method,
            url,
          ,
        ),
      )
      open.apply(this, [method, url, async !== undefined ? async : true, username, password])
    
    this.addEventListener(
      'readystatechange',
      () => 
        if (this.readyState === 4) 
          window.dispatchEvent(
            new CustomEvent('ajax_interceptor', 
              detail: 
                method: this.method,
                status: this.status,
                url: this.responseURL,
                response: this.response,
              ,
            ),
          )
        
      ,
      false,
    )
  


if (window.fetch) 
  const Fetch = window.fetch
  window.fetch = (url, init) => 
    window.dispatchEvent(
      new CustomEvent('ajax_interceptor_start', 
        detail: 
          methods: init?.method || 'GET',
          url,
        ,
      ),
    )
    return Fetch(url, init).then(async response => 
      const data = await response.clone().text()
      window.dispatchEvent(
        new CustomEvent('ajax_interceptor', 
          detail: 
            methods: init?.method || 'GET',
            status: response.status,
            url: response.url,
            response: data,
          ,
        ),
      )
      return response
    )
  


以上是关于请求拦截 XMLHttpRequest和fetch的主要内容,如果未能解决你的问题,请参考以下文章

可以将 Fetch API 用作请求拦截器吗?

开源一款好用的AJAX和FETCH拦截器

跨域CORS

fetch请求数据

XMLHttpRequest 成功,而 fetch 被阻止

Fetch