// 简易实现axios封装
const my_axios = (config: any) => {
// 返回一个promise对象
return new Promise((resolve, reject) => {
// 使用xhr实现功能
const xhr = new XMLHttpRequest()
// 如果有查询参数进行转换拼接
if (config.params) {
const params = new URLSearchParams(config.params)
config.url += `?${params.toString()}`
}
xhr.open(config.method || 'Get', config.url)
xhr.addEventListener("loadend", () => {
if (xhr.status == 200) {
resolve(xhr.response)
} else {
reject(xhr)
}
})
// 如果有数据,则设置请求行并发送请求
if (config.data) {
const data = JSON.stringify(config.data)
xhr.setRequestHeader("Content-Type", "application/json")
xhr.send(data)
} else {
xhr.send()
}
})
}
//测试
my_axios({
url: '',
method: 'POST',
data: {
username: '',
password: ''
}
}).then(result => {
console.log(result);
}).catch(error => {
console.log(error);
})
简单实现axios封装
最新推荐文章于 2024-10-17 09:40:47 发布