/**
这种是不是很简单,他是基于promise封装过了,
**/
axios({
url: ‘https://cnodejs.org/api/v1/topics’
}).then(res => {
console.log(res);
})
//这是不是一个函数调用?,调用里面写了实参,形参是不是要去接受,形参要接受,什么有
形参,函数
咱先看如何封装的 默认是get可以传post和get
function axios({
method = “get”,
async = true,
url
})
{
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest()
xhr.open(method, url, async);
xhr.send();
// onreadystatechange监听请求状态的变化 0 1 2 3 4 五个状态 4表示请求服务器数据成功
xhr.onreadystatechange = function() {
//4 请求成功了,但是突然断网了,是不是还要状态码200成功
if (xhr.readyState === 4 && xhr.status === 200) {
// console.log(xhr.responseText);
let data = JSON.parse(xhr.responseText)
// console.log(data);
resolve(data)
}
}
})
}
单纯封装get,超简单
axios.get = function(url) {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest()
xhr.open(‘get’, url, true);
xhr.send();
// onreadystatechange监听请求状态的变化 0 1 2 3 4 五个状态 4表示请求服务器数据成功
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
// console.log(xhr.responseText);
let data = JSON.parse(xhr.responseText)
// console.log(data);
resolve(data)
}
}
})
}
使用get
axios.get(‘https://cnodejs.org/api/v1/topics’).then(res => {
console.log(res);
})
post
axios.post = function(url) {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest()
xhr.open(‘post’, url, true);
xhr.send();
// onreadystatechange监听请求状态的变化 0 1 2 3 4 五个状态 4表示请求服务器数据成功
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
// console.log(xhr.responseText);
let data = JSON.parse(xhr.responseText)
// console.log(data);
resolve(data)
}
}
})
}
打印结果

源码
本文详细解释了如何使用axios库对HTTP请求进行Promise封装,包括GET和POST方法的实现,以及如何处理异步请求的状态变化和响应数据。
2291

被折叠的 条评论
为什么被折叠?



