export class Http {
static async getJson(url) {
const response = await fetch(url);
return response.json();
}
static async sendForm(url, params = {}) {
const response = await fetch(url, {
method: "POST",
headers: {
"X-Requested-With": "fetch",
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams(params),
});
if (!response.ok) {
throw new Error(`request failed with status ${response.status}`);
}
return response.json();
}
static async postJson(url, body) {
const response = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
if (!response.ok) {
throw new Error(`request failed with status ${response.status}`);
}
return response.json();
}
static postForm(action, data = {}) {
const form = document.createElement("form");
form.method = "POST";
form.action = action;
for (const [name, value] of Object.entries(data)) {
const input = document.createElement("input");
input.type = "hidden";
input.name = name;
input.value = value;
form.appendChild(input);
}
document.body.appendChild(form);
form.submit();
}
}
window.Http = Http;