Files
wedding-site/server/frontend/main/api.js
MH.Dmitrii 1534181e71
All checks were successful
Build Docker / deploy (push) Successful in 1m5s
Build Docker / build (push) Successful in 50s
error handling
2026-05-10 17:24:32 +03:00

96 lines
3.3 KiB
JavaScript

document.addEventListener("DOMContentLoaded", () => {
// Проверка авторизации через cookie
fetch('/api/verify', { credentials: 'include' })
.then(r => { if (!r.ok) window.location.href = '/'; })
.catch(() => { window.location.href = '/'; });
// Logout — удаляем cookie на бэкенде
document.getElementById('logoutForm').addEventListener('click', async function(e) {
e.preventDefault();
await fetch('/api/logout', {
method: 'POST',
credentials: 'include'
});
window.location.href = '/';
});
document.querySelector(".form-connect").addEventListener("submit", async (e) => {
e.preventDefault();
const guestData = {
name: document.getElementById('ffname').value || "",
middlename: document.getElementById('fmname').value || "",
surname: document.getElementById('flname').value || "",
text_field: document.getElementById('text_field')?.value || "",
activated: true,
types_of_food: document.querySelector('input[name="food"]:checked')?.value || "",
types_of_alco: Array.from(document.querySelectorAll('input[name="drink"]:checked'))
.map(el => el.value)
.join(', ')
};
try {
const response = await fetch('/api/update', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include', // ← токен идёт через cookie
body: JSON.stringify(guestData)
});
if (!response.ok) {
const err = await response.json();
throw new Error(JSON.stringify(err.detail || 'Ошибка при отправке'));
}
const data = await response.json();
console.log('Успешно:', data);
alert('Данные сохранены!');
} catch (err) {
console.error(err);
showErrors(err.message);
}
});
});
const fieldMap = {
'name': 'ffname',
'middlename': 'fmname',
'surname': 'flname'
};
function showErrors(errors) {
let errorElements = document.querySelectorAll(".formError")
if (errorElements.length === 0) {
document.querySelectorAll('.label_style').forEach(el => {
const errorElem = document.createElement('div');
errorElem.className = 'formError';
errorElem.style.cssText = `
color: red;
margin-top: 10px;
margin-bottom: 10px;
font-size: 14px;
font-weight: 100;
line-height: 120%;
transition: 3s;
`;
el.after(errorElem);
});
}
errors.forEach(error => {
const fieldName = error.loc[1]; // 'name', 'middlename', 'surname'
const inputId = fieldMap[fieldName];
if (!inputId) return;
const input = document.getElementById(inputId);
if (!input) return;
const label = input.closest('.label_style');
if (label && label.nextElementSibling?.classList.contains('formError')) {
label.nextElementSibling.textContent = error.msg;
}
});
}