从其他路由调用登录检查路由时无法获取Cookie的问题
问题原因与解决方案
你遇到的问题核心是fetch请求默认不会携带Cookie。当你在/loggedinbyanotherway路由里用fetch调用/loggedin时,这个内部请求并没有把用户浏览器传来的Cookie带上,所以/loggedin路由里的req.cookies.jwt自然是undefined,最终返回false。
推荐解决方案:复用验证逻辑
没必要通过内部HTTP请求调用另一个路由,把登录验证逻辑抽成独立函数,两个路由直接调用即可,既高效又避免Cookie传递问题:
// 抽离登录验证逻辑为独立函数 const isUserLoggedIn = (req) => { try { const token = req.cookies.jwt; if (!token) return false; jwt.verify(token, process.env.JWT_SECRET); return true; } catch (err) { // 处理token过期、无效等情况 if (err.name === 'TokenExpiredError' || err.name === 'JsonWebTokenError') { return false; } throw err; // 真正的服务器错误再抛出 } }; // 原路由直接调用验证函数 router.get('/loggedin', async (req, res) => { try { const isLoggedIn = isUserLoggedIn(req); res.send(isLoggedIn); } catch (err) { res.status(500).send(false); } }); // 新路由同样调用验证函数 router.get('/loggedinbyanotherway', async (req, res) => { try { const isLoggedIn = isUserLoggedIn(req); res.send(isLoggedIn); } catch (err) { res.status(500).send(false); } });
备选方案:强制fetch携带Cookie(不推荐)
如果坚持要用内部fetch调用,需要给fetch配置credentials: 'include',同时确保Cookie的domain和path配置允许内部请求携带:
router.get('/loggedinbyanotherway', async (req, res) => { const checking = await fetch(`${process.env.API_URL}:${process.env.PORT || 3000}/loggedin`, { credentials: 'include' // 关键:携带Cookie }); const data = await checking.json(); res.send(data); });
这种方式完全是多此一举,额外的HTTP请求会增加服务器开销,优先选择复用逻辑的方案。
内容的提问来源于stack exchange,提问作者GinDev
相关产品推荐
相关产品推荐

