adfba467474c6bceae4bc13c784e671a0de3d7be
1 import params
from "../parameters"; //for server URL
3 // TODO: replace by fetch API ?
4 // https://www.sitepoint.com/xmlhttprequest-vs-the-fetch-api-whats-best-for-ajax-in-2019/
5 // Problem: fetch() does not set req.xhr... see access/ajax() security especially for /whoami
7 // From JSON (encoded string values!) to "arg1=...&arg2=..."
8 function toQueryString(data
)
11 Object
.keys(data
).forEach(k
=> {
12 data_str
+= k
+ "=" + encodeURIComponent(data
[k
]) + "&";
14 return data_str
.slice(0, -1); //remove last "&"
17 // data, error: optional
18 export function ajax(url
, method
, data
, success
, error
)
20 let xhr
= new XMLHttpRequest();
21 if (data
=== undefined || typeof(data
) === "function") //no data
28 success
= () => {}; //by default, do nothing
30 error
= errmsg
=> { alert(errmsg
); };
31 xhr
.onreadystatechange = function() {
32 if (this.readyState
== 4 && this.status
== 200)
36 res_json
= JSON
.parse(xhr
.responseText
);
38 // Plain text (e.g. for rules retrieval)
39 return success(xhr
.responseText
);
41 if (!res_json
.errmsg
&& !res_json
.errno
)
45 if (!!res_json
.errmsg
)
46 error(res_json
.errmsg
);
48 error(res_json
.code
+ ". errno = " + res_json
.errno
);
53 if (["GET","DELETE"].includes(method
) && !!data
)
55 // Append query params to URL
56 url
+= "/?" + toQueryString(data
);
58 xhr
.open(method
, params
.serverUrl
+ url
, true);
59 xhr
.setRequestHeader('X-Requested-With', "XMLHttpRequest");
60 // Next line to allow cross-domain cookies in dev mode (TODO: if...)
62 xhr
.withCredentials
= true;
63 if (["POST","PUT"].includes(method
))
65 xhr
.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
66 xhr
.send(JSON
.stringify(data
));