function myAxios(config){
return new Promise((resolve,reject)=>{
const xhr = new XMLHttpRequest()
// 1.判断有params选项,携带查询参数
if(config.params){
// 2.使用URLSearchParams转换,并携带到url上
const paramsObj = new URLSearchParams(config.params)
const queryString = paramsObj.toString()
// 把查询参数字符串拼接在url?后面
config.url += `?${queryString}`
}
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))
}
})
xhr.send()
})
}
myAxios({
url:'https://api-hmugo-web.itheima.net/api/public/v1/goods/detail',
params:{
goods_id:1
}
}).then(result=>{
console.log(result);
})
版权属于:
公子初心
作品采用:
《
署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)
》许可协议授权
评论 (0)