Promise手撕axios,(它是咋用原生封装的)

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

/**

这种是不是很简单,他是基于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)

}

}

})

}

打印结果

源码

Document
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值