You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Cookie存在状态创建Pug条件判断时遇‘Document未定义’错误

问题原因与解决办法

你遇到的Document is not defined错误核心原因是:document是浏览器端DOM环境的专属对象,Node.js后端运行环境里根本不存在这个对象,你混淆了前后端的Cookie处理逻辑。


解决步骤

1. 安装并启用cookie-parser中间件

Express框架默认不会自动解析请求中的Cookie,需要借助cookie-parser中间件把请求里的Cookie解析到req.cookies对象中,方便后端读取:

  • 先安装依赖:
    npm install cookie-parser
    
  • 在Express入口文件(比如app.js)中引入并启用:
    const cookieParser = require('cookie-parser');
    app.use(cookieParser());
    

2. 修改后端登录状态判断逻辑

把原来依赖浏览器document.cookie的判断逻辑,改成从后端请求对象req中读取Cookie:

方式一:封装成可复用函数

function loggedIn(req) {
  // 检查请求Cookie中是否存在userName字段,转成布尔值返回
  return !!req.cookies.userName;
}

// 路由中调用
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Cinema', login: loggedIn(req)});     
});

方式二:直接在路由内判断(更简洁)

router.get('/', function(req, res, next) {
  const isLoggedIn = !!req.cookies.userName;
  res.render('index', { title: 'Cinema', login: isLoggedIn});     
});

3. Pug模板中正常使用条件判断

现在可以通过传入的login变量,在模板里渲染不同内容:

if login
  div.login-status
    h1 欢迎回来,#{req.cookies.userName}!
    a(href="/logout") 退出登录
else
  div.unlogin-status
    h1 欢迎访问Cinema
    a(href="/login") 立即登录

内容的提问来源于stack exchange,提问作者Quinten1208

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 00:14:57