custom-axios
v1.0.2
Published
axios
Downloads
1
Readme
自定义axios库
简单的实现
function axios({url,method='GET',params={},data={}}) {
return new Promise((resolve,reject) => {
//创建xml对像
const xhr = new XMLHttpRequest();
let queryString = '';
Object.keys(params).forEach(key => {
queryString += `${key} = ${params[key]}&`
});
if(queryString) {
queryString = queryString.substring(0,queryString.length - 1);
url += '?' + queryString;
}
//打开连接
xhr.open(method,url,true);
//发送请求
if(method === 'GET') {
xhr.send();
} else if(method === 'POST') {
//设置请求状
xhr.setRequestHeader('Content-Type','application/json;charset=utf-8')
xhr.send(JSON.stringify(data))
}
//绑定状态的临听
xhr.onreadystatechange = (req) => {
if(xhr.readyState !==4) {
return
}
const { status,statusText } = xhr;
if(status >= 200 && status <=299) {
const response = {
data:JSON.parse(xhr.response),
status,
statusText
}
console.log('response',response);
resolve(response);
} else {
reject(new Error('request error status is' + status))
}
}
})
}
module.exports = axios;