adfba467474c6bceae4bc13c784e671a0de3d7be
[vchess.git] / client / src / utils / ajax.js
1 import params from "../parameters"; //for server URL
2
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
6
7 // From JSON (encoded string values!) to "arg1=...&arg2=..."
8 function toQueryString(data)
9 {
10 let data_str = "";
11 Object.keys(data).forEach(k => {
12 data_str += k + "=" + encodeURIComponent(data[k]) + "&";
13 });
14 return data_str.slice(0, -1); //remove last "&"
15 }
16
17 // data, error: optional
18 export function ajax(url, method, data, success, error)
19 {
20 let xhr = new XMLHttpRequest();
21 if (data === undefined || typeof(data) === "function") //no data
22 {
23 error = success;
24 success = data;
25 data = {};
26 }
27 if (!success)
28 success = () => {}; //by default, do nothing
29 if (!error)
30 error = errmsg => { alert(errmsg); };
31 xhr.onreadystatechange = function() {
32 if (this.readyState == 4 && this.status == 200)
33 {
34 let res_json = "";
35 try {
36 res_json = JSON.parse(xhr.responseText);
37 } catch (e) {
38 // Plain text (e.g. for rules retrieval)
39 return success(xhr.responseText);
40 }
41 if (!res_json.errmsg && !res_json.errno)
42 success(res_json);
43 else
44 {
45 if (!!res_json.errmsg)
46 error(res_json.errmsg);
47 else
48 error(res_json.code + ". errno = " + res_json.errno);
49 }
50 }
51 };
52
53 if (["GET","DELETE"].includes(method) && !!data)
54 {
55 // Append query params to URL
56 url += "/?" + toQueryString(data);
57 }
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...)
61 if (params.cors)
62 xhr.withCredentials = true;
63 if (["POST","PUT"].includes(method))
64 {
65 xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
66 xhr.send(JSON.stringify(data));
67 }
68 else
69 xhr.send();
70 }