-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsdk_http.js
98 lines (79 loc) · 2.85 KB
/
sdk_http.js
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/*
* sdk的http模块
*
* create by zengxx on 2018-11-22
*/
let logManager = require('./sdk_log');
// Http 实例
let _instance = null;
class Http {
static get instance () {
if (!_instance) {
_instance = new Http();
}
return _instance;
}
post (cfgObj, successcb, failcb) {
try {
let useJson = false;
let xhr = new XMLHttpRequest();
xhr.open('POST', cfgObj.url);
if (cfgObj.headers) {
for (let k in cfgObj.headers) {
xhr.setRequestHeader(k.toString(), cfgObj.headers[k]);
if ((k == 'content-type' || k == 'Content-type') && cfgObj.headers[k] == 'application/json;charset=UTF-8') {
useJson = true;
}
}
}
if (typeof(cfgObj.headers) != 'object') {
cfgObj.headers = {
'content-type': 'application/x-www-form-urlencoded;charset:UTF-8'
};
}
xhr.onreadystatechange = function () {
logManager.LOGD('http.post responseText ' + xhr.responseText);
if(xhr.readyState == 4 && xhr.status==200){
if (typeof xhr.responseText === 'string') {
successcb && successcb(JSON.parse(xhr.responseText));
}else{
failcb && failcb();
}
}
};
logManager.LOGD('http.post send... ' + cfgObj.url + '\n' + JSON.stringify(cfgObj.postData));
if (useJson) {
xhr.send(JSON.stringify(cfgObj.postData));
} else {
let formData = new FormData();
for (let k in cfgObj.postData) {
formData.append(k.toString(), cfgObj.postData[k]);
}
xhr.send(formData);
}
} catch (err) {
logManager.LOGE('error:', 'Http.post... ' + JSON.stringify(err));
}
}
get (cfgObj, successcb, failcb) {
try {
let xhr = new XMLHttpRequest();
xhr.open('GET', cfgObj.url);
xhr.onreadystatechange = function(e) {
logManager.LOGD('http.get responseText ' + xhr.responseText);
if(xhr.readyState == 4 && xhr.status==200){
if (typeof xhr.responseText === 'string') {
successcb && successcb(JSON.parse(xhr.responseText));
}else{
failcb && failcb();
}
}
};
logManager.LOGD('http.get send... ' + cfgObj.url);
xhr.send();
} catch(err) {
logManager.LOGE('error:', 'Http.get... ' + JSON.stringify(err));
}
}
}
module.exports = Http.instance;