手写 实现 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);
  });
}

.

posted @ 2021-05-08 12:00  每天都要进步一点点  阅读(310)  评论(0编辑  收藏  举报