使用XHR封装的简单无拦截axios

150 阅读1分钟

本文已参与[新人创作礼]活动,一起开启掘金创作之路

一.使用XHR发送get请求

    // 创建
    let xhr = new XMLHttpRequest
    // 方法和路径
    xhr.open('GET', '地址')
    // 发送
    xhr.send()
    // 接受
    xhr.onload = function () {
      console.log(xhr.response);
    console.log(JSON.parse(xhr.response).data);
    }

二.使用XHR发送post请求

    // 创建
    let xhr = new XMLHttpRequest
    // 方法和路径
    xhr.open('post', '地址')
    // 传参1 需要设置头信息 a=1&b=2&c=3
    // let data = '数据'
    // xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
    // 传参2 需要设置头信息 json格式字符串
    let data1 = JSON.stringify({
            变量名:变量值
    })

    xhr.setRequestHeader('content-type', 'application/JSON')
    // 发送
    xhr.send(data1)
    // 接受
    xhr.onload = function () {
      console.log(xhr.response);     
      console.log(JSON.parse(xhr.response).data);
    }

三.使用XHR封装的axios

03 common.js

// 模拟函数
// fake({
//   method: '请求方法',
//   url: '路径',
//   params: '查询参数', //  无参 字符串 对象
//   data: '请求体参数', // FormData 字符串  对象
//   // 这里没有使用Promise的then()只是模拟相同的效果
//   sccess: function (res) {
//     // res是服务端响应数据
//     console.log(res);
//   }
// })


// 封装一个办法 把对象转换为a=1&b=2&c=3类型的字符串
function objTostring(obj) {
  let arr = []
  for (let k in obj) {
    // k = obj[k]
    // k 是属性名    obj[k]是属性值
    arr.push(`${k}=${obj[k]}`)
  }
  return arr.join('&')
}
function fake(config) {
  // 1 创建
  let xhr = new XMLHttpRequest
  // 4 接受
  xhr.onload = function () {
    let obj = JSON.parse(xhr.response)
    // console.log(obj)
    config.sccess(obj)
  }

  // 下面要根据不同的请求 设置不同的处理
  // toUpperCase() // 转换大写   toLowerCase()  // 转换小写 
  if (config.method.toUpperCase() == 'GET') {
    if (typeof config.params == 'undefined') {
      // 2 设置
      xhr.open('GET', config.url)
    }
    else if (typeof config.params == 'string') {
      // 2 设置
      xhr.open('GET', config.url + '?' + config.params)
    }
    else if (typeof config.params == 'object') {
      // 2 设置  
      xhr.open('GET', config.url + '?' + objTostring(config.params))
    }
    // 3 发送
    xhr.send()
  } else if (config.method.toUpperCase() == 'POST') {
    // 2 设置
    xhr.open('POST', config.url)
    if (config.data instanceof FormData) {
      // 3 发送
      xhr.send(config.data)
    } else if (typeof config.data == 'string') {
      xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
      // 3 发送
      xhr.send(config.data)
    } else if (typeof config.data == 'object') {
      xhr.setRequestHeader('content-type', 'application/JSON')
      // 3 发送
      xhr.send(JSON.stringify(config.data))
    }
  }
}

四.使用

 <script src="./03 common.js"></script>
  <script>
    fake({
      url: '地址',
      method: 'get',
      params: '变量名:变量值&变量名:变量值',
      sccess: function (res) {
        console.log(res);
      }
    })

    fake({
      url: '地址',
      method: 'post',
      data: {
        变量名:变量值
      },
      sccess: function (res) {
        console.log(res);
      }
    })
  </script>