Skip to content

Commit 6c433fa

Browse files
committed
add a form post API
1 parent 63a5973 commit 6c433fa

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

src/JsonService.js

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,4 +81,73 @@ export class JsonService {
8181
req.send();
8282
});
8383
}
84+
85+
postForm(url, payload) {
86+
if (!url){
87+
Log.error("JsonService.postForm: No url passed");
88+
throw new Error("url");
89+
}
90+
91+
Log.debug("JsonService.postForm, url: ", url);
92+
93+
return new Promise((resolve, reject) => {
94+
95+
var req = new this._XMLHttpRequest();
96+
req.open('POST', url);
97+
98+
var allowedContentTypes = this._contentTypes;
99+
100+
req.onload = function() {
101+
Log.debug("JsonService.postForm: HTTP response received, status", req.status);
102+
103+
if (req.status === 200) {
104+
105+
var contentType = req.getResponseHeader("Content-Type");
106+
if (contentType) {
107+
108+
var found = allowedContentTypes.find(item=>{
109+
if (contentType.startsWith(item)) {
110+
return true;
111+
}
112+
});
113+
114+
if (found) {
115+
try {
116+
resolve(JSON.parse(req.responseText));
117+
return;
118+
}
119+
catch (e) {
120+
Log.error("JsonService.postForm: Error parsing JSON response", e.message);
121+
reject(e);
122+
return;
123+
}
124+
}
125+
}
126+
127+
reject(Error("Invalid response Content-Type: " + contentType + ", from URL: " + url));
128+
}
129+
else {
130+
reject(Error(req.statusText + " (" + req.status + ")"));
131+
}
132+
};
133+
134+
req.onerror = function() {
135+
Log.error("JsonService.postForm: network error");
136+
reject(Error("Network Error"));
137+
};
138+
139+
let body = "";
140+
for(let key in payload) {
141+
if (body.length > 0) {
142+
body += "&";
143+
}
144+
body += encodeURIComponent(key);
145+
body += "=";
146+
body += encodeURIComponent(payload[key]);
147+
}
148+
149+
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
150+
req.send(body);
151+
});
152+
}
84153
}

0 commit comments

Comments
 (0)