php使用axios发送请求,axios源码之模拟实现axios发送请求

axios内部运作流程大致如下axios入口-

->axios构造函数-

->interceptors请求拦截器-

->dispatchRequest方法-

->transformRequest请求转换器-

->adapter适配器-

->transformResponse响应转换器-

->interceptors响应拦截器

具体模拟实现axios使用dispatchRequest方法,以及adapter适配器发送一个异步请求的核心代码//模拟axios发送请求

//1、声明构造函数

function Axios(config){

this.config = config;

}

//为Axios的原型对象添加request方法,axios(),axios.get()等,核心就是调axios.request()方法

Axios.prototype.request = function(config){

//创建一个promise对象

let promise = Promise.resolve(config);

//声明一个数组,保存promise的then方法的两个参数

let chains = [dispatchRequest, undefined]; //undefined作用是占位

//调用then方法,指定回调

let result = promise.then(chains[0],chains[1]);

//返回promise的结果

return result;

}

//2、dispatchRequest函数

function dispatchRequest(config){//该函数的返回结果必须是一个promise对象

//调用适配器发送请求

return xhrAdapter(config).then(response => {

//省略对响应结果进行转换处理

return response;

},error=>{

throw error;

})

}

//3、adapter适配器

function xhrAdapter(config){ //该函数的返回值也是promise

return new Promise((resolve,reject)=>{

//不考虑请求体的发送,创建一个异步请求

let xhr = new XMLHttpRequest();

xhr.open(config.method, config.url);

xhr.send();

//绑定事件

xhr.onreadystatechange = function(){

if(xhr.readyState === 4) {

if(xhr.status >= 200 && xhr.status < 300) {

resolve({

//自定义返回数据

config: config, //配置对象

data: xhr.response, //响应体

headers: xhr.getAllResponseHeaders(),

request: xhr,//请求对象

status: xhr.status,//响应状态码

statusText: xhr.statusText //响应状态字符串

})

} else {

reject(new Error('请求失败状态码为'+xhr.status))

}

}

}

})

}

//测试创建axios函数

let axios = Axios.prototype.request.bind(null)

//用axios发送请求

axios({

method:'GET',

url:'http://localhost:3000/posts'

}).then(res=>{

console.log(res)

})

bVcQDDS

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值