You need to enable JavaScript to run this app. Node.js使用passport-local-mongoose报TypeError: cb is not a function如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Node.js使用passport-local-mongoose报TypeError: cb is not a function如何解决

问题根因

你调用passport-local-mongoose提供的User.register方法时传入的参数数量与方法定义不匹配,这是报错的核心原因:

  • 从源码可见register方法仅接收3个参数:(用户信息对象, 明文密码, 回调函数)
  • 你额外传入了req.body.email作为第二个参数,导致方法将第三个位置的密码字符串识别为回调函数,调用时抛出cb is not a function错误。
  • 数据能正常入库是因为方法内部的存储逻辑已经执行完成,但回调调用失败,后续的页面跳转逻辑没有触发,所以页面一直处于加载状态。
修复方法

将email字段放入第一个用户信息对象中,调整register方法的入参顺序即可,修改后的路由代码如下:

app.post("/sign-up",(req,res)=>{
  const username = req.body.username
  const email = req.body.email
  const password = req.body.password

  // 调整参数:把email放入第一个用户对象,删除多余的第二个参数
  User.register({username: username, email: email}, req.body.password, (err,user)=>{
    if(err){
      console.log(err);
      res.redirect("/sign-up")
    }else{
      passport.authenticate("local" )(req,res, function (){
        res.redirect('/compose')
      })
    }
  })
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 23:18:02