简易版axios实现-基于promise+XMLHttpRequest

    /**
     * 目标:封装_简易axios函数_获取省份列表
     *  1. 定义myAxios函数,接收配置对象,返回Promise对象
     *  2. 发起XHR请求,默认请求方法为GET
     *  3. 调用成功/失败的处理程序
     *  4. 使用myAxios函数,获取省份列表展示
    */
    function myAxios(config) {
      return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest()
        // 查询参数支持
        if (config.params) {
          config.url += `?${new URLSearchParams(config.params).toString()}`
        }
        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))
          }
        })
        // 请求体参数支持
        if (config.data) {
          xhr.setRequestHeader("Content-Type", "application/json")
          xhr.send(JSON.stringify(config.data))
        } else {
          xhr.send()
        }
      })
    }

    myAxios({
      url: "https://ajax.itheima.net/api/register",
      method: "post",
      data: {
        username: "mayanan04",
        password: "123456"
      }
    }).then(ret => {
      document.querySelector("p").innerHTML = ret.message
    }).catch(err => {
      document.querySelector("p").innerHTML = err.message
    })

相关推荐

  1. 简易axios实现-基于promise+XMLHttpRequest

    2024-03-09 23:42:09       23 阅读
  2. 实现简易axios

    2024-03-09 23:42:09       18 阅读
  3. 基于asio的httpclient实现

    2024-03-09 23:42:09       34 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-09 23:42:09       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-09 23:42:09       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-09 23:42:09       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-09 23:42:09       18 阅读

热门阅读

  1. ESP32系列四:搭建http的webserver的服务器

    2024-03-09 23:42:09       25 阅读
  2. C++17之std::invoke: 使用和原理探究(全)

    2024-03-09 23:42:09       21 阅读
  3. Flutter第二弹:Widget

    2024-03-09 23:42:09       21 阅读
  4. C++ 类的前向声明的用法

    2024-03-09 23:42:09       25 阅读
  5. 【面试题】mysql常见面试题及答案总结

    2024-03-09 23:42:09       19 阅读
  6. vue3 使用 mock 模拟服务器接口

    2024-03-09 23:42:09       30 阅读
  7. c++虚函数

    2024-03-09 23:42:09       24 阅读
  8. 【git】总结

    2024-03-09 23:42:09       21 阅读
  9. [R]To delete a dataset from the environment

    2024-03-09 23:42:09       25 阅读
  10. xml总结

    2024-03-09 23:42:09       21 阅读