enhance error handling for register

This commit is contained in:
2026-01-26 20:28:25 +01:00
parent 8fe362c966
commit 0e9fedc9b4
2 changed files with 55 additions and 0 deletions

View File

@@ -126,6 +126,58 @@ window.requestAnimFrame = (function () {
registerModal.style.display = 'none'; registerModal.style.display = 'none';
} }
}); });
const registerForm = registerModal.querySelector('form');
if (registerForm) {
registerForm.addEventListener('submit', async (e) => {
e.preventDefault();
const formData = new FormData(registerForm);
const params = new URLSearchParams(formData);
try {
const res = await fetch('/register', {
method: 'POST',
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: params
});
if (res.redirected) {
window.location.href = res.url;
return;
}
const text = await res.text();
let json;
try {
json = JSON.parse(text);
} catch (e) { }
if (json && json.success === false) {
let errDiv = registerForm.querySelector('.flash-error');
if (!errDiv) {
errDiv = document.createElement('div');
errDiv.className = 'flash-error';
errDiv.style.color = '#ff4444';
errDiv.style.textAlign = 'center';
errDiv.style.marginBottom = '10px';
errDiv.style.fontWeight = 'bold';
registerForm.insertBefore(errDiv, registerForm.firstChild); // Insert before h2 or inputs
// Actually firstChild is text or h2. Let's insert after H2 if possible?
// The form has H2 as first element roughly.
// insertBefore firstChild is fine, it puts it at top.
}
errDiv.textContent = json.msg;
}
} catch (err) {
console.error('Registration error:', err);
}
});
}
} }
// Initialize background preference // Initialize background preference

View File

@@ -15,6 +15,9 @@ export default (router, tpl) => {
const { username, password, password_confirm, token } = req.post; const { username, password, password_confirm, token } = req.post;
const renderError = (msg) => { const renderError = (msg) => {
if (req.headers['x-requested-with'] === 'XMLHttpRequest' || (req.headers.accept && req.headers.accept.includes('application/json'))) {
return res.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify({ success: false, msg }));
}
return res.reply({ return res.reply({
body: tpl.render("register", { theme: req.cookies.theme ?? "f0ck", error: msg }) body: tpl.render("register", { theme: req.cookies.theme ?? "f0ck", error: msg })
}); });