zoukankan      html  css  js  c++  java
  • 手写 实现 axios

    axios 本质是 xhr 外层包裹 Promise

    代码:

    function axios(url, formdata) {
      return new Promise(function (resolve, reject) {
        let xhr = null;
    
        if (window.XMLHttpRequest) {
          xhr = new XMLHttpRequest();
        } else {
          try {
            xhr = new ActiveXObject("Microsoft.XMLHTTP");
          } catch {
            xhr = new ActiveXObject("smxml2.XMLHTTP");
          }
        }
    
        xhr.open("POST", url);
    
        xhr.onreadystatechange = () => {
          if (xhr.readyState === 4 && xhr.status === 200) {
            const result = JSON.parse(xhr.responseText);
            resolve(result);
          }
        };
    
        xhr.onerror = (err) => {
          reject(err);
        };
    
        xhr.setRequestHeader("Authorization", `Bearer ....`);
    
        xhr.send(formdata);
      });
    }

    .

  • 相关阅读:
    SCUT
    SCUT
    SCUT
    ???
    Codeforces
    SCUT
    SCUT
    SCUT
    SCUT
    2019牛客暑期多校训练营(第八场)
  • 原文地址:https://www.cnblogs.com/crazycode2/p/14748279.html
Copyright © 2011-2022 走看看