使用XMLHttpRequest对象封装自己的axios函数

公子初心
2024-02-18 / 0 评论 / 27 阅读 / 正在检测是否收录...

    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);
    })
0

评论 (0)

取消