js实现强制登录
实现强制登录的 JavaScript 方法
检查登录状态
通过检查本地存储(localStorage)或会话存储(sessionStorage)中的登录凭证来判断用户是否已登录。若未登录,则跳转到登录页面。
if (!localStorage.getItem('authToken')) {
window.location.href = '/login.html';
}
路由拦截
在单页应用(SPA)中,可以通过路由守卫拦截未登录的访问请求。使用框架如 Vue Router 或 React Router 实现。
// Vue Router 示例
router.beforeEach((to, from, next) => {
const isAuthenticated = localStorage.getItem('authToken');
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login');
} else {
next();
}
});
后端验证
前端发送请求时,后端应验证用户凭证的有效性。若凭证无效,返回 401 状态码,前端据此跳转到登录页面。
fetch('/api/protected', {
headers: {
'Authorization': `Bearer ${localStorage.getItem('authToken')}`
}
}).then(response => {
if (response.status === 401) {
window.location.href = '/login.html';
}
});
定时检查会话
设置定时器定期检查会话是否过期,避免用户长时间未操作导致会话失效。
setInterval(() => {
fetch('/api/check-session', {
headers: {
'Authorization': `Bearer ${localStorage.getItem('authToken')}`
}
}).then(response => {
if (response.status === 401) {
window.location.href = '/login.html';
}
});
}, 300000); // 每5分钟检查一次
全局错误处理
通过全局错误处理捕获未授权的请求,统一跳转到登录页面。

window.addEventListener('unhandledrejection', event => {
if (event.reason.status === 401) {
window.location.href = '/login.html';
}
});
注意事项
- 敏感操作应结合后端验证,仅依赖前端验证不安全。
- 登录凭证建议使用 HttpOnly 的 Cookie 存储,避免 XSS 攻击。
- 跳转登录页时,可携带当前页面 URL 作为参数,登录后自动跳回原页面。






