export default async (url = "", data = {}, type = "GET", method = "fetch") => {
let baseUrl = "";
type = type.toUpperCase();
url = baseUrl + url;
if (type == "GET") {
let dataStr = ""; //数据拼接字符串
Object.keys(data).forEach((key) => {
dataStr += key + "=" + data[key] + "&";
});
if (dataStr !== "") {
dataStr = dataStr.substr(0, dataStr.lastIndexOf("&")); //截取最后一个 ‘&’ 符号
url = url + "?" + dataStr;
}
}
if (window.fetch && method == "fetch") {
let requestConfig = {
credentials: "include",
method: type,
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
mode: "cors",
cache: "force-cache",
};
if (type == "POST") {
//Object.defineProperty() 方法会直接在一个对象上定义一个新属性,或者修改一个对象的现有属性,并返回此对象。
Object.defineProperty(requestConfig, "body", {
value: JSON.stringify(data),
});
}
try {
const response = await fetch(url, requestConfig);
const responseJson = await response.json();
return responseJson;
} catch (error) {
throw new Error(error);
}
} else {
return new Promise((resolve, reject) => {
let requestObj;
if (window.XMLHttpRequest) {
requestObj = new XMLHttpRequest();
} else {
requestObj = new ActiveXObject();
}
let sendData = "";
if (type == "POST") {
sendData = JSON.stringify(data);
}
requestObj.open(type, url, true);
requestObj.setRequestHeader(
"Content-type",
"application/x-www-form-urlencoded"
);
requestObj.send(sendData);
requestObj.onreadystatechange = () => {
if (requestObj.readyState == 4) {
if (requestObj.status == 200) {
let obj = requestObj.response;
if (typeof obj !== "object") {
obj = JSON.parse(obj);
}
resolve(obj);
} else {
reject(requestObj);
}
}
};
});
}
};
js 统一封装 api 请求文件 ----window.fetch方法
最新推荐文章于 2023-09-05 06:48:40 发布