65 lines
2.4 KiB
JavaScript
65 lines
2.4 KiB
JavaScript
document.getElementById('loginForm').addEventListener('submit', async function (e) {
|
|
e.preventDefault();
|
|
const email = document.getElementById('email').value;
|
|
const password = document.getElementById('password').value;
|
|
const userData = {
|
|
email,
|
|
password
|
|
};
|
|
try {
|
|
const response = await fetch('http://localhost:8000/login', {
|
|
method: 'POST',
|
|
headers: {
|
|
'Accept': 'application/json',
|
|
'Content-Type': 'application/json'
|
|
},
|
|
body: JSON.stringify(userData)
|
|
});
|
|
|
|
const data = await response.json(); // читаем только один раз
|
|
|
|
if (response.ok) {
|
|
localStorage.setItem("token", data.access_token); // сохраняем только при успехе
|
|
window.location.href = './../main/index.html';
|
|
} else {
|
|
if (Array.isArray(data.detail)) {
|
|
const messages = data.detail.map(e => {
|
|
const field = e.loc.filter(locPart => locPart !== 'body').join(' -> ');
|
|
return `${field}: ${e.msg}`;
|
|
});
|
|
showError(messages);
|
|
} else if (typeof data.detail === 'string') {
|
|
showError([data.detail]);
|
|
} else {
|
|
showError(['Unknown error']);
|
|
}
|
|
}
|
|
} catch (err) {
|
|
showError(['Connection error: ' + err.message]);
|
|
}
|
|
});
|
|
function showError(messages){
|
|
let errorElem = document.getElementById('formError');
|
|
let container = document.getElementById('glass-container');
|
|
if (!errorElem){
|
|
errorElem = document.createElement('div');
|
|
errorElem.style.transition="3s";
|
|
errorElem.id = 'formError';
|
|
errorElem.style.color = 'red';
|
|
errorElem.style.marginTop = '20px';
|
|
errorElem.style.fontSize = '14px';
|
|
errorElem.style.fontWeight = '100';
|
|
errorElem.style.marginBottom = '20px';
|
|
errorElem.style.lineHeight="120%";
|
|
errorElem.style.height = 'auto';
|
|
const form = document.getElementById('loginForm');
|
|
form.insertAdjacentElement('afterend', errorElem);
|
|
};
|
|
errorElem.innerHTML = '';
|
|
messages.forEach(msg => {
|
|
const li = document.createElement('li');
|
|
li.style.listStyleType="none";
|
|
li.textContent = msg;
|
|
errorElem.appendChild(li);
|
|
});
|
|
} |