Javascript xhr helper

Date: 2019-11-01
(() => {
    const xhrError = (xhr, message) => {
        const error = new Error(message);
        error.xhr = xhr;
        return error;
    };

    const formDataUrlEncoded = (data) => {
        var str = [];
        if (data) {
            Object.keys(data).forEach((key) => str.push(encodeURIComponent(key) + "=" + encodeURIComponent(data[key])));
        }
        return str.join("&");
    };

    const baseRequest = (method, url, headers, postData, responseType, timeout) => {
        return new Promise(function (resolve, reject) {
            const xhr = new XMLHttpRequest();
            xhr.responseType = responseType;
            xhr.timeout = timeout || xhr.timeout;
            xhr.open(method, url, true);
            Object.keys(headers || {}).forEach((key) => xhr.setRequestHeader(key, headers[key]));            
            xhr.addEventListener("error", (event) => reject(xhrError(xhr, "Network error (" + url + ")")));
            xhr.addEventListener("timeout", (event) => reject(xhrError(xhr, "Timeout error (" + url + ")")));
            xhr.addEventListener("load", (event) => resolve(xhr));
            xhr.send(postData);
        });
    };

    const httpRequest = (url, data, settings) => {
        settings = settings || {};
        const method = (settings.method || "GET").toUpperCase();
        const contentType = settings.contentType || "x-www-form-urlencoded";
        const responseType = settings.responseType || "text"; // text | arraybuffer | ...
        let postData = null;        
        if (method === "POST" || method === "PUT") {
            if (contentType === "x-www-form-urlencoded") {
                postData = formDataUrlEncoded(data);
            } else if (typeof data !== "string") {
                postData = JSON.stringify(data);
            } else {
                postData = data;
            }
        } else if (data) {
            url += "?" + formDataUrlEncoded(data);
        }
        return baseRequest(method, url, settings.headers, postData, responseType, settings.timeout)
            .then((xhr) => {
                const success = xhr.status >= 200 && xhr.status < 400;
                return { xhr, data: xhr.responseText, success };
            });
    };

    httpRequest('http://localhost:4200/').then((xhr) => console.log(xhr.responseText));
})();
28000cookie-checkJavascript xhr helper