function myAxios(config) {
return new Promise((resolve,reject) => {
const xhr = new XMLHttpRequest()
if (config.params) {
const params = new URLSearchParams(config.params)
const query = params.toString()
config.url += `?${query}`
}
xhr.open(config.method || 'GET',config.url)
xhr.addEventListener('loadend', () => {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(JSON.parse(xhr.response))
} else {
reject(new Error(xhr.response))
}
})
if (config.data) {
xhr.setRequestHeader('Content-Type','application/json')
xhr.send(JSON.stringify(config.data))
} else {
xhr.send()
}
})
}
myAxios({
url : ''
}).then(res => {
console.log(res)
})
myAxios({
url : '',
params : {
pname : '广东省'
}
}).then(res => {
console.log(res)
})
myAxios({
url : '',
method : 'POST',
data : {
username : '两袖清风怎敢误佳人',
password : 'wyfmrl'
},
}).then(res => {
console.log(res)
})
封装简易axios函数
发布时间 2023-09-22 21:24:03作者: 唯有风