res.redirect无响应求助:前端请求后无法跳转至登录页
问题原因
当你用fetch发起AJAX请求时,后端的res.redirect()并不会触发浏览器页面跳转——这是fetch的默认行为:它会自动跟随重定向(即使你设置了redirect: 'follow'),但只会获取重定向目标页面的内容,不会主动修改当前浏览器的URL或加载新页面。只有浏览器主动发起的导航请求(比如地址栏输入、点击a标签、调用window.location.href),才会在收到后端重定向响应时触发页面跳转。
解决方案
方案1:后端返回认证状态,前端手动跳转(推荐,更灵活)
修改后端代码,返回包含认证状态和跳转地址的JSON:
app.get('/user/verify', (req, res) => { if (req.session.authenticated) { res.json({ authenticated: true }); // 执行你的业务逻辑 } else { console.log('You have reached the else statement'); res.json({ authenticated: false, redirectUrl: '/pages/login.html' }); } });
前端代码根据返回结果手动跳转:
async function verify() { const options = { method: 'GET', }; const response = await fetch('/user/verify', options); const result = await response.json(); if (!result.authenticated) { window.location.href = result.redirectUrl; } else { // 已认证,执行后续逻辑 } } window.addEventListener('click', (event) => { if (event.target.id == 'taskbar-user') { verify(); } });
方案2:放弃AJAX,直接发起浏览器导航请求
如果不需要在验证过程中做额外AJAX逻辑,可以直接在点击时让浏览器发起导航请求,这样后端的res.redirect()就能正常触发页面跳转:
window.addEventListener('click', (event) => { if (event.target.id == 'taskbar-user') { window.location.href = '/user/verify'; } });
这种方式下,后端原有代码不需要修改,浏览器会自动处理重定向响应并跳转到登录页。
内容的提问来源于stack exchange,提问作者LostInTheCSSauce
相关产品推荐
相关产品推荐

