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

使用Nodemailer与JWT实现邮箱验证时,JWT解析后用户ID始终为undefined的问题排查

邮箱验证中JWT解析userId为undefined的问题排查与修复

我看了你的代码,问题出在JWT解析时的解构操作上,咱们来一步步理清:

错误原因

你在创建JWT的时候,payload传的是{ userId: newUser.id }——也就是说,解析后得到的对象里,userId字段直接对应用户的ID值,而不是一个包含id属性的嵌套对象。但在验证路由里,你写了这样的解构:

const { userId: { id }, } = jwt.verify(req.params.token, "SECRETKEY");

这相当于试图从userId这个值里再取出id属性,可userId本身就是ID字符串/数字,根本没有id属性,所以id自然会变成undefined,导致后续更新数据库时出现WHERE参数无效的错误。

修复方案

把解构语句改成正确的形式,直接取出userId即可,有两种写法可选:

写法一:直接取出userId,后续使用userId作为ID值

app.get("/api/confirmMail/:token", async (req, res) => {
  try {
    // 正确解构出userId
    const { userId } = jwt.verify(req.params.token, "SECRETKEY");
    // 使用userId作为更新条件的id值
    await user.update({ confirmed: 1 }, { where: { id: userId } });
  } catch (err) {
    console.log(err);
  }
  return res.redirect("http://localhost:3000/login");
});

写法二:解构时重命名为id,保持后续代码不变

app.get("/api/confirmMail/:token", async (req, res) => {
  try {
    // 解构时将userId重命名为id
    const { userId: id } = jwt.verify(req.params.token, "SECRETKEY");
    await user.update({ confirmed: 1 }, { where: { id: id } });
  } catch (err) {
    console.log(err);
  }
  return res.redirect("http://localhost:3000/login");
});

额外检查建议

你也可以在创建用户之后加个console.log(newUser),确认数据库返回的用户对象确实包含id字段——不过从当前错误信息来看,核心问题肯定是解构操作的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 13:19:11