使用XMLHttpRequest与Promise封装Axios
基于 Promise 和 XHR 封装 Axios 函数
实现步骤
- 定义 getAxios 函数,接收配置对象,返回 Promise 对象
- 使用xmlHttpRequest 请求,默认请求方法为 GET
- 使用then/catch成功/失败的处理程序
- 使用 getAxios 函数,调用天气接口
- 总结:axios封装可以多式多样,本文应该是最简单的封装了
function getAxios(config) {
return new Promise((resolve, reject) => {
const xmlHttpRequest = new XMLHttpRequest()
if (config.params) {
const queryString = new URLSearchParams(config.params).toString()
config.url += `?${queryString}`
}
xmlHttpRequest.open(config.method || 'GET', config.url)
xmlHttpRequest.addEventListener('loadend', () => {
if (xmlHttpRequest.status >= 200 && xmlHttpRequest.status < 300) {
resolve(JSON.parse(xmlHttpRequest.response))
} else {
reject(new Error(xmlHttpRequest.response))
}
})
if (config.data) {
const dataStr = JSON.stringify(config.data)
xmlHttpRequest.setRequestHeader('Content-Type', 'application/json')
xmlHttpRequest.send(dataStr)
} else {
xmlHttpRequest.send()
}
})
}
//可以根据请求调整使用模板
getAxios({
url: '',
method: '',
params: '',
data: {}
}).then(result => {
console.log(result)
}).catch(error => {
console.log(error)
})