原生xhr、fetch 請求的攔截。mock 技術原理


一、原生ajax對象【xhr、fetch】 請求的攔截: https://m.imooc.com/mip/wenda/detail/603075【通過改寫send方法,使原有的send方法失效】   或  https://www.cnblogs.com/xiaoyuxy/p/12346344.html 【通過 自帶的 中斷 方法 實現。沒有測試過】

  1、xhr 通過 XMLHttpRequest 的原型上 設置 send 方法,使得 原來的send 方法失效 ,就發送不了 請求了。

XMLHttpRequest.prototype.send = function () {
  //  在 XMLHttpRequest 原型上設置 了send 方法,原來的send 失效。
};

var xmlhttp = new XMLHttpRequest();
  xmlhttp.open("GET", "/try/ajax/demo_get.php", true);
  xmlhttp.send(); // xmlhttp.send() 自帶 的發送行為 失效了。

  xmlhttp.onreadystatechange = function () {
    console.log("pp", xmlhttp.readyState);
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      console.log("dffa");
    }
  };

  猜想:mock.js 應該就是通過這種方式實現的。

 

二、mock.js

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM