在JavaScript中实现登录和注销功能通常涉及到前端与后端的交互,以及本地存储(如localStorage
或sessionStorage
)的使用来管理用户的登录状态。以下是一个简单的实现示例:
<form id="loginForm">
<input type="text" id="username" placeholder="用户名" required>
<input type="password" id="password" placeholder="密码" required>
<button type="submit">登录</button>
</form>
document.getElementById('loginForm').addEventListener('submit', function(event) {
event.preventDefault(); // 阻止表单默认提交行为
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
// 发送登录请求到后端API
fetch('/api/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ username, password })
})
.then(response => response.json())
.then(data => {
if (data.success) {
// 登录成功,保存token到localStorage
localStorage.setItem('userToken', data.token);
// 更新UI,显示登录后的状态
} else {
// 登录失败,显示错误信息
alert(data.message);
}
})
.catch(error => console.error('Error:', error));
});
function logout() {
// 清除localStorage中的用户token
localStorage.removeItem('userToken');
// 更新UI,显示登录前的状态
}
// 假设有一个注销按钮
document.getElementById('logoutButton').addEventListener('click', logout);
function logout() {
const token = localStorage.getItem('userToken');
if (token) {
// 发送注销请求到后端API
fetch('/api/logout', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`
}
})
.then(response => response.json())
.then(data => {
if (data.success) {
// 后端注销成功,清除localStorage中的用户token
localStorage.removeItem('userToken');
// 更新UI,显示登录前的状态
}
})
.catch(error => console.error('Error:', error));
}
}
HttpOnly
的cookie中,以防止XSS攻击,或者使用sessionStorage
而不是localStorage
,因为sessionStorage
在浏览器关闭后会被清除。以上代码仅为示例,实际应用中需要根据具体需求和安全规范进行调整。
领取专属 10元无门槛券
手把手带您无忧上云