window.onload = function() { autoLogin(); }; var checkInfo = {}; checkInfo.checkMobileNo = function() { let mobileNo = document.getElementById('mobileNo').value; let regexMobileNo = /^1[3-9]\d{9}$/; if (!regexMobileNo.test(mobileNo)) { document.getElementById('mobileNoError').textContent = '手机号格式有误'; return false; } document.getElementById('mobileNoError').textContent = ''; return true; } checkInfo.checkPassword = function() { let password = document.getElementById('password').value; let regexPassword = /^[A-Za-z0-9\W_]{6,20}$/; if (!regexPassword.test(password)) { document.getElementById('loginError').textContent = "密码须为长度为6-20位字母、数字或符号"; return false; } document.getElementById('loginError').textContent = ''; return true; } function submitForm() { if (checkInfo.checkMobileNo() && checkInfo.checkPassword()) { document.getElementById('encryptedPassword').value = md5( document.getElementById('password').value ); login(); return true; } return false; } // 登录函数 async function login() { const mobileNo = document.getElementById('mobileNo').value; const encryptedPassword = document.getElementById('encryptedPassword').value; try { const response = await fetch('/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: mobileNo, password: encryptedPassword }), credentials: 'include' // 确保请求包含凭据(cookies) }); const data = await response.json(); if (response.ok) { alert('登录成功'); // 自动跳转到主页 window.location.href = data.redirect; } else { document.getElementById('loginError').textContent = data.message; } } catch (error) { alert('数据库错误,请稍后再试'); } } // 自动登录函数 async function autoLogin() { const token = localStorage.getItem('token'); if (token) { const response = await fetch('http://localhost:5000/index', { headers: { 'Authorization': 'Bearer ' + token } }); if (response.ok) { document.getElementById('content').innerText = '已自动登录'; } else { document.getElementById('content').innerText = '自动登录失败'; } } }