Files
toolbox/api/static/js/api.js
T

32 lines
812 B
JavaScript

// api.js
export async function apiRequest(url, payload = {}, method = 'POST') {
method = method.toUpperCase();
let finalUrl = url;
let options = {
method,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
credentials: 'same-origin'
};
// --- Если GET → добавляем payload в URL ---
if (method === 'GET') {
const params = new URLSearchParams(payload);
finalUrl = `${url}?${params.toString()}`;
} else {
// --- Для остальных методов → отправляем body ---
options.body = JSON.stringify(payload);
}
const res = await fetch(finalUrl, options);
if (!res.ok) {
const text = await res.text();
throw new Error(`HTTP ${res.status}: ${text}`);
}
return res.json();
}