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);
  });
}

.

相关文章:

  • 2021-06-25
  • 2021-09-28
  • 2021-08-01
  • 2021-11-25
  • 2021-12-19
  • 2021-10-05
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-08-07
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-31
相关资源
相似解决方案