js简易封装成axios

219 阅读1分钟
import { axiosBaseURL } from './axios/config'

// 封装axios
export const myAxios = function (options = {}) {
    myAxios.createDef = myAxios.createDef || {};
    // 默认参数
    myAxios._default = {
        method: 'GET',
        url: '',
        baseURL: axiosBaseURL,
        cache: false,
        data: null,
        params: null,
        headers: {},
        dataType: 'JSON',
    };
    // 参数整合
    let { method, url, baseURL, cache, data, params, headers, dataType } = {
        ...myAxios.createDef,
        ...myAxios._default,
        ...options
    };

    // 检测参数   get系列
    if (/^(get|delete|head|options)$/ig.test(method)) {
        if (params) {
            url += /\?/g.test(url) ? '&' + myAxios.paramsSerializer(params) : '?' + myAxios.paramsSerializer(params);
        }
        if (cache === false) {
            url += /\?/g.test(url) ? '&_=' + new Date() : '?_=' + new Date();
        }
    } else {
        if (data) {
            data = myAxios.paramsSerializer(data);
        }
    }
    return new Promise((resolve, reject) => {
        let xhr;
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xhr = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xhr = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xhr.open(method, `${baseURL}${url}`);
        if (headers && typeof headers == 'object') {
            for (let attr in headers) {
                if (!headers.hasOwnProperty(attr)) {
                    let val = /[\u4e00-\u9fa5]/.test(headers[attr]) ? encodeURIComponent(headers[attr]) : headers[attr];
                    xhr.setRequestHeader(attr, val);
                }
            }
        }

        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                //判断是否请求成功(Http状态码大于等于200,且小于300,和状态码等于304为请求成功)
                if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
                    resolve(xhr.responseText);
                } else {
                    reject(xhr.responseText);
                }
            }
        }
        xhr.send(data);
    })
    myAxios.paramsSerializer = function (params) {
        if (typeof params == 'string') {
            return params;
        }
        if (!params) {
            return null;
        }
        if (typeof params == 'object') {
            let res = '';
            for (let attr in params) {
                res += `${attr}=${params[attr]}&`;
            }
            res = res.substring(0, res.length - 1);
            return res;
        }
    };
    myAxios.all = function (data) {
        return Promise.all(data);
    };
    myAxios.spread = function (callback) {
        return function (arg) {
            callback.apply(null, arg);
        }
    };
    myAxios.create = function (options) {
        if (options && typeof options == 'object') {
            myAxios.createDef = options;
        }
    };

    ['get', 'delete', 'head', 'options'].forEach(item => {
        myAxios[item] = function (url, options = {}) {
            options = {
                ...options,
                url: url,
                method: item.toUpperCase()
            };
            return myAxios(options);
        }
    });
    ['post', 'put', 'patch'].forEach(item => {
        myAxios[item] = function (url, data = {}, options = {}) {
            options = {
                ...options,
                url: url,
                method: item.toUpperCase(),
                data: data,
            };
            return myAxios(options);
        }
    });

};