X-Git-Url: https://git.auder.net/?a=blobdiff_plain;f=client%2Fsrc%2Futils%2Fajax.js;h=eb30330a7b7bb9a77ff1932819bd45af4777c129;hb=317b8a5610953b30cfb84382bd13764177ce830b;hp=0a50a10409ac1c332b84e141f61a110846b72c0f;hpb=1aeed627be63a298d3a093797c3728e3de30b464;p=vchess.git diff --git a/client/src/utils/ajax.js b/client/src/utils/ajax.js index 0a50a104..eb30330a 100644 --- a/client/src/utils/ajax.js +++ b/client/src/utils/ajax.js @@ -1,5 +1,9 @@ import params from "../parameters"; //for server URL +// TODO: replace by fetch API ? +// https://www.sitepoint.com/xmlhttprequest-vs-the-fetch-api-whats-best-for-ajax-in-2019/ +// Problem: fetch() does not set req.xhr... see access/ajax() security especially for /whoami + // From JSON (encoded string values!) to "arg1=...&arg2=..." function toQueryString(data) { @@ -14,15 +18,16 @@ function toQueryString(data) export function ajax(url, method, data, success, error) { let xhr = new XMLHttpRequest(); - if (typeof(data) === "function") //no data + if (data === undefined || typeof(data) === "function") //no data { error = success; success = data; data = {}; } + if (!success) + success = () => {}; //by default, do nothing if (!error) error = errmsg => { alert(errmsg); }; - xhr.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { @@ -33,10 +38,15 @@ export function ajax(url, method, data, success, error) // Plain text (e.g. for rules retrieval) return success(xhr.responseText); } - if (!res_json.errmsg) + if (!res_json.errmsg && !res_json.errno) success(res_json); else - error(res_json.errmsg); + { + if (!!res_json.errmsg) + error(res_json.errmsg); + else + error(res_json.code + ". errno = " + res_json.errno); + } } }; @@ -47,8 +57,8 @@ export function ajax(url, method, data, success, error) } xhr.open(method, params.serverUrl + url, true); xhr.setRequestHeader('X-Requested-With', "XMLHttpRequest"); - // Next line because logout and authenticate set (cross-domain in dev mode) cookies - if (url.startsWith("/authenticate") || url.startsWith("/logout")) + // Next line to allow cross-domain cookies in dev mode (TODO: if...) + if (params.cors) xhr.withCredentials = true; if (["POST","PUT"].includes(method)) {