Started code review + some fixes (unfinished)
[vchess.git] / client / src / utils / ajax.js
CommitLineData
03470390
BA
1import params from "../parameters"; //for server URL
2
e64c6f67
BA
3// TODO: replace by fetch API ?
4// https://www.sitepoint.com/xmlhttprequest-vs-the-fetch-api-whats-best-for-ajax-in-2019/
317b8a56 5// Problem: fetch() does not set req.xhr... see access/ajax() security especially for /whoami
e64c6f67 6
da06a6eb 7// From JSON (encoded string values!) to "arg1=...&arg2=..."
6808d7a1 8function toQueryString(data) {
dac39588
BA
9 let data_str = "";
10 Object.keys(data).forEach(k => {
11 data_str += k + "=" + encodeURIComponent(data[k]) + "&";
12 });
13 return data_str.slice(0, -1); //remove last "&"
da06a6eb
BA
14}
15
16// data, error: optional
6808d7a1 17export function ajax(url, method, data, success, error) {
dac39588 18 let xhr = new XMLHttpRequest();
6808d7a1
BA
19 if (data === undefined || typeof data === "function") {
20 //no data
dac39588
BA
21 error = success;
22 success = data;
23 data = {};
24 }
6808d7a1 25 if (!success) success = () => {}; //by default, do nothing
dac39588 26 if (!error)
6808d7a1
BA
27 error = errmsg => {
28 alert(errmsg);
29 };
dac39588 30 xhr.onreadystatechange = function() {
6808d7a1 31 if (this.readyState == 4 && this.status == 200) {
1aeed627 32 let res_json = "";
dac39588
BA
33 try {
34 res_json = JSON.parse(xhr.responseText);
1aeed627 35 } catch (e) {
6808d7a1
BA
36 // Plain text (e.g. for rules retrieval) (TODO: no more plain text in current version)
37 success(xhr.responseText);
1aeed627 38 }
6808d7a1
BA
39 if (res_json) {
40 if (!res_json.errmsg && !res_json.errno) success(res_json);
41 else {
42 if (res_json.errmsg) error(res_json.errmsg);
43 else error(res_json.code + ". errno = " + res_json.errno);
44 }
6f57a976 45 }
dac39588
BA
46 }
47 };
da06a6eb 48
6808d7a1 49 if (["GET", "DELETE"].includes(method) && !!data) {
dac39588
BA
50 // Append query params to URL
51 url += "/?" + toQueryString(data);
52 }
53 xhr.open(method, params.serverUrl + url, true);
6808d7a1 54 xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
4f298adb 55 // Next line to allow cross-domain cookies in dev mode
6808d7a1
BA
56 if (params.cors) xhr.withCredentials = true;
57 if (["POST", "PUT"].includes(method)) {
dac39588
BA
58 xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
59 xhr.send(JSON.stringify(data));
6808d7a1 60 } else xhr.send();
da06a6eb 61}