89 lines
2.5 KiB
JavaScript
89 lines
2.5 KiB
JavaScript
/* {http} v{version} | MIT | https:// */
|
|
(function(root, factory) {
|
|
/* eslint-disable */
|
|
if (typeof define === 'function' && define.amd) {
|
|
// AMD
|
|
define(['http'], factory);
|
|
} else if(typeof module === 'object' && module.exports) {
|
|
// CommonJS / NodeJS
|
|
module.exports = factory();
|
|
} else {
|
|
// Global
|
|
root.http = factory();
|
|
}
|
|
|
|
}(this, function() {
|
|
'use strict';
|
|
|
|
return function http(params, callback) {
|
|
// Any variable used more than once is var'd here because
|
|
// minification will munge the variables whereas it can't munge
|
|
// the object access.
|
|
var headers = params.headers || {}
|
|
, body = params.body
|
|
, method = params.method || (body ? 'POST' : 'GET')
|
|
, called = false;
|
|
|
|
var req = getRequest(params.cors);
|
|
|
|
var reqfields = [
|
|
'responseType', 'withCredentials', 'timeout', 'onprogress'
|
|
];
|
|
|
|
function getRequest(cors) {
|
|
if (window.XMLHttpRequest) {
|
|
return new XMLHttpRequest;
|
|
}
|
|
}
|
|
|
|
function setDefault(obj, key, value) {
|
|
obj[key] = obj[key] || value;
|
|
}
|
|
|
|
function cb(statusCode, responseText) {
|
|
return function () {
|
|
if (!called) {
|
|
callback(req.status === undefined ? statusCode : req.status,
|
|
req.status === 0 ? 'Error' : (req.response || req.responseText || responseText),
|
|
req);
|
|
called = true;
|
|
}
|
|
};
|
|
}
|
|
|
|
req.open(method, params.url, true);
|
|
|
|
var success = req.onload = cb(200);
|
|
req.onreadystatechange = function () {
|
|
if (req.readyState === 4) success();
|
|
};
|
|
|
|
req.onerror = cb(null, 'Error');
|
|
req.ontimeout = cb(null, 'Timeout');
|
|
req.onabort = cb(null, 'Abort');
|
|
|
|
if (body) {
|
|
setDefault(headers, 'X-Requested-With', 'XMLHttpRequest');
|
|
|
|
if (!window.FormData || !(body instanceof window.FormData)) {
|
|
setDefault(headers, 'Content-Type', 'application/x-www-form-urlencoded');
|
|
}
|
|
}
|
|
|
|
for (var i = 0, len = reqfields.length, field; i < len; i++) {
|
|
field = reqfields[i];
|
|
if (params[field] !== undefined) {
|
|
req[field] = params[field];
|
|
}
|
|
}
|
|
|
|
for (let field in headers) {
|
|
req.setRequestHeader(field, headers[field]);
|
|
}
|
|
|
|
req.send(body);
|
|
|
|
return req;
|
|
}
|
|
}));
|