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

MERN项目JWT认证时报Cannot read property 'jwtoken' of undefined如何解决

问题修复方案

1. 修复运行时报错:TypeError: Cannot read property 'jwtoken' of undefined

这个错误是因为你没有安装和配置cookie-parser中间件,Express默认无法解析请求携带的Cookie,所以req.cookies为undefined,访问它的jwtoken属性就会报错。

修复步骤:

  • 安装依赖:
npm install cookie-parser
  • 在app.js中引入并注册中间件,注意要放在所有路由注册之前:
const cookieParser = require('cookie-parser');
// 放在app.use(express.json())之后,路由注册之前
app.use(cookieParser());

2. 修复VSCode提示:Property '_id' does not exist on type 'string | JwtPayload'

jwt.verify()的返回值类型是联合类型,可能是字符串也可能是JwtPayload对象,所以直接取_id属性会触发类型校验报错。

修复方案:

在authenticate.js中调用jwt.verify后,先判断返回值是对象且存在_id属性,再进行后续操作:

const verifyToken = jwt.verify(token, process.env.SECRET_KEY);
// 新增校验逻辑
if (typeof verifyToken !== 'object' || verifyToken === null || !('_id' in verifyToken)) {
  throw new Error("无效的令牌载荷");
}
// 后续的findOne逻辑可以正常运行
const rootUser = await User.findOne({_id: verifyToken._id, "tokens.token": token});

如果是TypeScript项目,也可以直接用类型断言:

const verifyToken = jwt.verify(token, process.env.SECRET_KEY) as { _id: string };

3. 修复VSCode提示:Property 'rootUser' does not exist on type 'Request'

你在中间件中给req对象新增了rootUser、token、userID三个自定义属性,Express默认的Request类型定义中没有这些属性,所以触发类型报错。

修复方案:

  • 如果是JavaScript项目:直接在报错行上方添加注释忽略类型校验即可:
// @ts-ignore
res.send(req.rootUser);
  • 如果是TypeScript项目:扩展Express的Request类型定义,新建@types/express/index.d.ts文件,内容如下:
import express from "express";
declare global {
  namespace Express {
    interface Request {
      rootUser: any;
      token: string;
      userID: string;
    }
  }
}

然后在tsconfig.json的include配置项中添加该类型文件的路径即可。

额外的逻辑bug修复

你当前signin路由的逻辑顺序存在安全问题:无论用户密码是否正确,只要用户存在就会生成JWT并写入Cookie。需要调整逻辑顺序,先校验密码正确性,再生成令牌:

if (userLogin) {
  const isMatch = await bcrypt.compare(password, userLogin.password)
  // 先判断密码是否匹配
  if (!isMatch) {
    return res.status(400).json({ error: "Invalid Credentials" })
  }
  // 密码正确后再生成token、写入cookie
  token = await userLogin.generateAuthToken();
  console.log(token)
  res.cookie("jwtoken",token,{
    expires:new Date(Date.now()+25892000000),
    httpOnly:true
  })
  res.status(200).json({ message: "Login Success" })
}

内容的提问来源于stack exchange,提问作者Harsh Raj Ambastha

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 18:54:04