Kirby
首页
文章
随笔书签提示词AI 助手

简易Axios函数的封装

2024-07-14·
次浏览

AI 摘要

生成中...

目标:封装简易axios函数,注册用户

  1. 判断有data选项,携带请求体
  2. 转换数据类型,在send中发送
  3. 使用myAxios函数,完成注册用户
1234567891011121314151617181920212223242526272829303132333435363738
function myAxios(config) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
 
    if (config.params) {
      const paramsObj = new URLSearchParams(config.params)
      const queryString = paramsObj.toString()
      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))
      }
    })
    if (config.data) {
      const jsonStr = JSON.stringify(config.data)
      xhr.setRequestHeader('Content-Type', 'application/json')
      xhr.send(jsonStr)
    } else {
      xhr.send()
    }
  })
}
 
myAxios({
  url: 'http://hmajax.itheima.net/api/area',
  params: {
    pname: '辽宁省',
    cname: '大连市',
  },
}).then((res) => {
  console.log(res)
  document.querySelector('.my-p').innerHTML = res.list.join('<br>')
})

上一篇Flexbox: flex-1 和 flex-shrink-0 使用post,
下一篇图片上传和本地存储调用post,