在使用axios库时不知道什么原因一直到下面的错误
Current environment does not provide a require() for requiring ‘util’.
所以打算自己使用xhr封装一下
封装的代码如下
const ajax = ({
method = ‘get’,
url = ‘’,
params = undefined,
data = undefined,
responseType = ‘json’,
headers = {
'Content-Type': 'application/json'
},
timeout = 5000
}: config) => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
if (params) {
url = url + '?' + new URLSearchParams(params).toString()
}
xhr.open(method, url);
xhr.responseType = responseType;
const headKeyArr = Object.keys(headers)
// 设置请求头
for (let key of headKeyArr) {
xhr.setRequestHeader(key, headers[key])
}
// 处理请求体
let requestData = null;
if (data) {
if (data instanceof FormData) {
// data是FormData类型
requestData = data;
} else if (data instanceof URLSearchParams) {
// data是URLSearchParams类型
requestData = data.toString();
// 如用户设置了content-type请求头,则不作修改
if (!headers["content-type"]) {
xhr.setRequestHeader(
"content-type",
"application/x-www-form-urlencoded"
);
}
} else if (typeof data === "object") {
// data为普通对象
// 只转化为JSON或url编码字符串
if (
headers["content-type"] === "application/x-www-form-urlencoded" ||
headers["content-type"] === "application/json"
) {
if (headers["content-type"] === "application/x-www-form-urlencoded") {
const params = new URLSearchParams(data);
requestData = params.toString();
} else {
requestData = JSON.stringify(data);
}
} else {
// 默认情况下转为JSON格式
requestData = JSON.stringify(data);
if (!headers["content-type"]) {
xhr.setRequestHeader("content-type", "application/json");
}
}
}
}
let timer = null;
xhr.addEventListener('loadend', () => {
clearTimeout(timer);
timer = null;
const status = xhr.status;
const msg = xhr.response.data?.msg
// 调用成功/失败的处理程序
if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
resolve(JSON.parse(xhr.response))
} else {
if (msg) {
console.error(msg)
} else {
if (status === 400) {
console.error('请求错误')
}
if (status === 404) {
console.error('接口地址不存在')
}
if (status === 403) {
console.error('拒绝访问')
}
if (status === 500) {
console.error('服务器错误')
}
}
reject(new Error(xhr.response))
}
})
// xhr.ontimeout = function (e) {
// reject(new Error('请求超时'))
// };
if (timeout > 0) {
xhr.timeout = timeout;
// xhr.timeout超时事件
xhr.ontimeout = function () {
clearTimeout(timer);
timer = null;
reject("请求超时");
};
// 监听xhr对象下面的onload事件
// 当xhr对象接收完响应数据后触发
// xhr.onload = function () {
// // 清除延时器
// clearTimeout(timer);
// timer = null;
// };
// 网络中断或无效url
xhr.onerror = function () {
// 清除延时器
clearTimeout(timer);
timer = null;
reject(new Error("Network Error"));
};
timer = setTimeout(() => {
// 请求超时机制双重保护,调用 abort 方法终止请求
if (timer) {
clearTimeout(timer);
timer = null;
xhr.abort();
reject("timeout");
}
}, timeout);
}
xhr.send(requestData);
});
}
