<body>
<button id="btn1">按钮1</button>
<button id="btn2">按钮2</button>
<script>
oBtn1 = document.getElementById('btn1');
oBtn2 = document.getElementById('btn2');
function axios({
method, //请求方式
url, // 请求地址
data, // 请求体参数 body
params // querystring 查询字符串参数
}) {
return new Promise((resolve, reject) => {
// 1.创建xhr对象
const xhr = new XMLHttpRequest();
// 2.绑定onreadystatechange事件 一次请求中这个事件函数触发4次 (0->1/1->2/2->3/3->4)
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
//响应返回了(但是成功,失败不知道)
if (xhr.status >= 200 && xhr.status < 300) {
// 响应成功
const response = { request: xhr, status: xhr.status, data: JSON.parse(xhr.responseText) }
resolve(response)
} else {
// 响应失败
reject("error")
}
}
}
/*
通常情况下:
GET、DELETE请求,只会有查询字符串参数
POST、PUT、PAtCH请求,既可以有请求参数,也可以有查询字符串参数
params: { name: 'jack', age: 18 }
--> url?name=jack&age=18
*/
method = method.toUpperCase();//将method的字母转成大写
let qs = '';
if (params) {
// 提取params中所有属性名成为一个数组
// ['name', 'age']
qs = Object.keys(params).reduce((p, key) => {
const value = params[key]
return p += `${key}=${value}$`
}, "?").slice(0, -1) //把最后的$给截取掉
}
// 3.设置请求信息(请求地址,请求方法)
xhr.open(method, url + qs);
let body = '';
if ((method === "POST" || method === "PATCH" || method === "PUT") && data) {
xhr.setRequestHeader("content-type", "application/json")
body = JSON.stringify(data);
}
// 4.发送请求
xhr.send(body);
})
}
//测试
oBtn1.onclick = function () {
axios({
method: "GET",
url: "http://localhost:3000/posts"
})
.then((value) => {
console.log(value)
})
.catch((reason) => {
console.log(reason)
})
}
oBtn2.onclick = function () {
axios({
method: "POST",
url: "http://localhost:3000/posts",
data: {
"title": "xhr",
"author": "axios",
}
})
.then((value) => {
console.log(value)
})
.catch((reason) => {
console.log(reason)
})
}
</script>
</body>
</html>
使用xhr封装axios
最新推荐文章于 2024-05-09 10:00:51 发布