- $fetch请求方法支持fetch和ajax的get,post 等方法,对异步请求对象的封装,增加了手动取消请求的能力。
今天对这部分代码进行测试时发现用ajax发送请求时会报一个promise错误,随后测试发现有部份代码写的有问题。随更新。
/**
* @Author Visupervi
* @Date 2019/12/16 10:55
* @Name fetch 封装
* @Param
* @Return
* @Description 对fetch封装,包含get,post ajax的post请求
*/
export default $fetch = async (url = "", data = {}, type = "GET", method = "fetch") => {
const time = 3000;
if (type.toLocaleLowerCase() === "get") {
let str = "";
Object.keys(data).map((item, index) => {
str += item + '=' + data[item] + '&';
});
if (str !== "") {
str = str.substr(0, str.lastIndexOf("&"));
url = url + "?" + str;
}
}
if (window.fetch && method === "fetch") {
let requestConfig = {
credentials: 'include',
method: type,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
mode: "cors",
cache: "force-cache"
};
//fetch中的post 的请求
if (type.toLocaleLowerCase() === "post") {
Object.defineProperty(requestConfig, 'body', {
value: JSON.stringify(data)
})
}
try {
const {body} = requestConfig;
const controller = new AbortController();
let timerId = null;
const {signal} = controller;
timerId = setTimeout(() => controller.abort(), time)
requestConfig = {
...requestConfig,
body,
signal
}
const response = await fetch(url, requestConfig);
return await response.json();
} catch (e) {
throw new Error(e)
}
} else {
return new Promise((resolve, reject) => {
let reqObj = !window.XMLHttpRequest ? new ActiveXObject : new XMLHttpRequest();
let sendData = "";
//ajax中的post请求
if (type.toLowerCase() === "post") {
sendData = JSON.stringify(data)
}
reqObj.open(type, url, true);
reqObj.timeout = time;
reqObj.setRequestHeader("Content-type", "application/json");
reqObj.send(sendData);
reqObj.onreadystatechange = () => {
if (reqObj.readyState !== 4) return;
if (reqObj.status >= 200 && reqObj.status < 400) {
resolve(JSON.parse(reqObj.response);
} else {
reject(reqObj.response)
}
}
})
}
}