function _fetch(path, option) {
return new Promise((res, rej) => {
const { method, data, timeout } = option || {};
let xhr = new XMLHttpRequest();
let str = objToStr(data);
if (method.toLowerCase() === "get") {
xhr.open(method, path + "?" + str, true);
xhr.send();
} else if (method.toLowerCase() === "post") {
xhr.open(method, path, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send();
}
let timer = setTimeout(() => {
xhr.abort();
rej(new Error(xhr.responseText));
}, timeout);
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) {
return;
}
if (timer) {
clearTimeout(timer);
}
if ((xhr.status >= 200 && xhr.status <= 300) || xhr.status === 304) {
res(xhr.responseText);
} else {
rej(new Error(xhr.responseText));
}
};
});
}
_fetch("http://www.baidu.com/", {
method: "GET",
data: { name: "12" },
timeout: 2000,
})
.then((response) => {
console.log(response);
})
.catch(() => {});
手写http request
最新推荐文章于 2024-11-08 15:54:38 发布