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

Passport.js实现认证时报Cannot read properties of undefined (reading 'initialize')错误如何解决

问题解决方案

1. 修复index.js中passport引入和调用错误

你当前报错的直接原因有两个:

  • index.js作用域未引入passport变量,仅引入了配置文件,导致passport为undefined
  • passport.initialize是可执行函数,需要调用后再传入express中间件,你当前直接传递了函数引用

修复步骤:
首先在index.js顶部添加passport引入:

const passport = require("passport");

再修改passport中间件注册代码:

// 原错误代码 app.use(passport.initialize);
app.use(passport.initialize());
app.use(passport.session());

2. 修复passport配置文件变量名错误

./config/passport的验证回调中,你定义的回调参数为done,但密码校验时错误使用了未定义的cb变量,会导致验证逻辑崩溃:

// 原错误代码
// if (isMatch) {
//   return cb(null, user);
// } else {
//   return cb(null, false);
// }

// 修复后
if (isMatch) {
  return done(null, user);
} else {
  return done(null, false);
}

3. 修复前后端提交逻辑不匹配问题

你前端使用axios异步提交请求,但后端passport配置的successRedirect/failureRedirect仅适用于同步表单提交场景,会导致前端接收到302重定向响应,无法执行自定义跳转逻辑。可修改登录路由为适配异步请求的写法:

const router = require("express").Router();
var passport = require("passport");

router.post("/login", (req, res, next) => {
  passport.authenticate("local", (err, user, info) => {
    if (err) return next(err);
    if (!user) return res.status(400).json({ message: "用户名或密码错误" });
    req.logIn(user, (err) => {
      if (err) return next(err);
      return res.json({ message: "登录成功" });
    })
  })(req, res, next);
});

module.exports = router;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 06:24:03