美文网首页
封装一个 axios 对象

封装一个 axios 对象

作者: 最尾一名 | 来源:发表于2019-04-24 18:25 被阅读0次

前言

之前一直在项目中使用 axios 来发送请求,了解了其原理之后,决定封装一个与其类似的对象。

实现

const axios = {};

axios.ajax = (url, options) => {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    let requestUrl = url;
    const {params, method, headers, body} = options;
    
    if (params) {
      const arr = [];
      // You can edit your params rules here !
      for (const [key, value] of Object.entries(params)) {
        const line = `${key}=${encodeURIComponent(value)}`;
        if (value !== '' && value !== null) {
          arr.push(line);
        }
      }
      requestUrl = `${url}?${arr.join('&')}`;
    }

    xhr.open(method, requestUrl);

    xhr.onload = () => {
      const data = JSON.parse(xhr.response);
      const result = {
        status: this.status,
        data: data || xhr.statusText
      };
      if (200 <= this.status && this.status <= 300) {
        return resolve(result);
      }
      return reject(result);
    };

    xhr.onerror = () => reject({
      status: this.status,
      data: data || xhr.statusText
    });

    // 设置 HTTP 请求头部,必须在 open() 和 send() 之间调用
    if (headers) {
      for (const [key, value] of Object.entries(headers)) {
        xhr.setRequestHeader(key, value);
      }
    }
    xhr.withCredentials = true;

    const csrftoken = Cookies.get('csrftoken');
    if (csrftoken) {
      xhr.setRequestHeader('X-CSRFToken', csrftoken);
    }
    xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');

    xhr.send(JSON.stringify(body));
  })
};

axios.get = (url, params) => axios.ajax(url, {
  method: 'get',
  params
});

axios.post = (url, body) => axios.ajax(url, {
  method: 'post',
  body
});

axios.put = (url, body) => axios.ajax(url, {
  method: 'put',
  body
});

axios.delete = (url, body) => axios.ajax(url, {
  method: 'delete',
  body
});

axios.patch = (url, body) => axios.ajax(url, {
  method: 'PATCH',
  body
});

export default axios;

相关文章

网友评论

      本文标题:封装一个 axios 对象

      本文链接:https://www.haomeiwen.com/subject/kpcngqtx.html