ajax封装成以promise风格调用
ajax详细用法请点击以下链接
https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/onreadystatechange
// 封装ajax请求
const axios = {
config: {
header: {
"Content-Type": "application/json; charset=utf-8" },
timeout: 10000,
async: true
},
setConfig({
header = {
},
timeout = 10000,
async = true
}) {
this.config.header = {
... this.config.header, ...header };
this.config.timeout = timeout;
this.config.async = async;
return this;
},
init(method, url, data) {
let {
header, timeout, async } = this.config, flag = ["GET", "DELETE"].includes(method);
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
flag ? xhr.open(method, `${
url}?${
Object.keys(data).map(key => `${
key}=${
data[key]}`).join("&")}`, async) : xhr.open(method, url, async);
// 设置超时时间 10秒
xhr.timeout = timeout;
// 设置请求头
Object.keys(header).forEach(k => {
xhr.setRequestHeader(k, header[k]);
})
flag ? xhr.send() : xhr.send(JSON.stringify(data));
xhr.onreadystatechange = () => {
if (xhr.readyState == 4 && xhr.status == 200) {
resolve(JSON.parse(xhr.responseText))
}
}
xhr.ontimeout = () => {
reject("请求超时")
}
// xhr.onload = () => {
// console.log("请求完成")
// }
xhr.onerror = err => {
reject("请求出错")
}
})
},
get(url, data = {
}) {
return this.init("GET", url, data);
},
post(url, data = {
}) {
return this.init("POST", url, data);
}
}
// 发个请求试试
axios.setConfig({
header: {
"token": "123456"
}
}).get("https://v1.hitokoto.cn?encode=json").then(data => {
console.log(data)
}, errMsg => {
console.log(errMsg)
})