/** * Fetch API helper function * @param {string} endpoint Endpoint URL * @param {string} method Method (GET, POST, etc.) * @param {Object} headers Headers to include in the request * @param {Object} body Body of the request * @param {Function} cbOK Callback function for successful response * @param {Function} cbError Callback function for error response */ function fetchAPI(endpoint, method, headers = {}, body = null, cbOK, cbError) { let url = window.location.origin + "/api/" + endpoint; let options = { method: method, headers: headers } if (body !== null) { options.body = JSON.stringify(body); if (!options.headers['Content-Type']) { options.headers['Content-Type'] = 'application/json'; } } fetch(url, options) .then(async (response) => { if (!response.ok) { let msg; try { let _xxx = await response.json(); msg = _xxx.message || response.statusText; } catch { msg = await response.statusText; } throw new Error(msg); } return response.json(); }) .then(data => { cbOK(data); }) .catch(error => { cbError(error); }); }