function itheimaAxios({ url, method}) {
// 1. 外面需要Promise对象, 所以创建一个并返回
return new Promise((resolve, reject) => {
// 2. 解构配置对象参数使用
let xhr = new XMLHttpRequest()
xhr.open(method, url)
xhr.send()
xhr.addEventListener('load', function () {
if(xhr.status >= 200 && xhr.status<400){
let result = JSON.parse(xhr.response)
resolve(result)
} else {
reject({message: xhr.response})
}
})
})
}
// 测试
itheimaAxios({
url: 'http://ajax-api.itheima.net/api/province',
method: 'GET'
}).then(res => {
console.log(res)
}).catch(err => {
console.error(err)
})