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;
custom-axios
1.0.2 • Public • PublishedReadme
Keywords
nonePackage Sidebar
Install
npm i custom-axios
Repository
Weekly Downloads
0
Version
1.0.2
License
MIT
Unpacked Size
17.2 kB
Total Files
10