-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.js
More file actions
executable file
·48 lines (39 loc) · 1.73 KB
/
http.js
File metadata and controls
executable file
·48 lines (39 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
module.exports = (function () {
return {
post: function (endpoint, form, config) {
return new Promise(function (resolve, reject) {
var xhr;
if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); }
else { xhr = new ActiveXObject("Microsoft.XMLHTTP"); }
xhr.open('POST', endpoint, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
for (var header in config.headers) {
xhr.setRequestHeader(header, config.headers[header]);
}
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
try {
resolve({ data: JSON.parse(xhr.responseText) });
} catch(e) {
resolve({ data: xhr.responseText });
}
} else {
reject({
message: 'Forbidden, server responded with status: ' + xhr.status,
data: xhr.responseText
})
}
}
}
xhr.onerror = function (event) { reject(event); };
let formParams = '';
for (let p in form) {
if (formParams.length) formParams += '&';
formParams += encodeURI(p + '=' + form[p]);
}
xhr.send(formParams);
})
}
}
})();