One-AnDong / PandaTalk

书写文字,让技术沉淀
1 stars 0 forks source link

使用promise封装了个简单的get请求 #2

Open One-AnDong opened 5 years ago

One-AnDong commented 5 years ago

封装过程

说到请求,我们可能会想到fetch,但我查看了mdn文档发现,还是有很多版本的浏览器不支持fetch,所以我就想到了原来的ajax,利用promise封装了个简单的函数,大致就是如下了

//简单封装ajax
export function ajaxGet(url) {
  return new Promise(function(resolve, reject) {
    const xhr = new XMLHttpRequest()
    xhr.open('GET', url)
    xhr.send(null)
    xhr.onreadystatechange = function() {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          try {
            const data = JSON.parse(xhr.response)
            resolve(data)
          } catch (error) {
            console.error(error)
          }
        } else {
          console.error('请求失败:', xhr.status)
          reject(xhr.status)
        }
      }
    }
  })
}
One-AnDong commented 5 years ago

今天也要超越昨天的自己 init

One-AnDong commented 5 years ago

模仿axios进行了第二次封装

class Ajax {
  /**
   * @date 2019-7-22
   * @author Joe
   * @param {Object} options [必选]
   */
  constructor(options) {
    this.options = Object.assign(
      {
        url: '',
        method: 'GET',
        mime: 'application/x-www-form-urlencoded',
        data: null,
        cache: false
      },
      options
    )
    //返回一个promise对象
    return this.promiseInstance()
  }
  getRandom() {
    return Date.now()
  }
  getUrl() {
    let url = this.options.url
    //判断如果是get请求,直接把参数填写在url中
    let isGet = /get||GET/.test(this.options.method)
    let cache = this.options.cache
    let symbol = this.options.url.indexOf('?') > -1 ? '&' : '?'
    if (isGet) {
      !cache ? (url += symbol + this.getRandom()) : null
    }
    return url
  }
  promiseInstance() {
    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest()
      const url = this.getUrl()
      const method = this.options.method
      //填写初始化请求地址和方式
      xhr.open(method, url)
      //判断如果是post请求,填写上请求头和请求体数据
      if (this.options.method === 'POST') {
        xhr.setRequestHeader('Content-type', this.options.mime)
        xhr.send(this.options.data)
      } else {
        xhr.send(null)
      }
      //判断ajax状态,4为响应数据解析完成
      xhr.onreadystatechange = () => {
        // 状态码不为4的时候直接return
        if (!xhr || xhr.readyState !== 4) return
        //粗糙返回一个对象
        const response = {
          data: xhr.responseText,
          status: xhr.status,
          statusText: xhr.statusText,
          headers: xhr.getAllResponseHeaders(),
          request: xhr
        }
        //status 状态为2xx 和 3xx的时候执行
        if (/^[2,3]\d{2}$/.test(xhr.status)) {
          resolve(response)
        } else {
          reject(response)
        }
      }
    })
  }
}
//对外暴露接口
export default Ajax
One-AnDong commented 5 years ago

新增加了几个方法,addr和setHost来实现简单的地址管理

const tool = {
  host: 'http://127.0.0.1:8080',
  addr(path) {
    return path.replace(/\/api/, this.host)
  },
  setHost(host) {
    this.host = host
  }
}

export { tool }