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

Express中Passport中间件在控制器中失效问题排查

Why Your Passport-Local Authentication Times Out in the Controller

The issue here boils down to how you’re using passport.authenticate in your controller. Let’s break it down simply:

passport.authenticate('local-signup', { ... }) doesn’t run the authentication logic right away—it returns a middleware function that needs req, res, and next arguments to do its work. In your current createUser method, you’re creating this middleware function but never actually executing it. That’s why your request times out: nothing is processing the authentication or sending a response back to the client.

Fixing the Controller Code

To fix this, you need to invoke the middleware function returned by passport.authenticate and pass it the req, res, and next parameters. Here’s the corrected controller.user.js:

const User = require('../models/user.js');
const passport = require('passport');
require('../../config/passport')(passport)

exports.login = (req, res) => {
  res.render('pages/login', { message: req.flash('loginMessage') });
};

exports.signup = (req, res) => {
  res.render('pages/signup', { message: req.flash('signupMessage') });
};

exports.createUser = (req, res, next) => {
  // Invoke the passport middleware with req, res, next to trigger authentication
  passport.authenticate('local-signup', {
    successRedirect : '/all',
    failureRedirect : '/signup',
    failureFlash : true
  })(req, res, next);
};

Why Moving It to the Route Works

When you place passport.authenticate directly in your route definition (like app.post('/signup', passport.authenticate(...))), Express automatically handles passing the req, res, and next arguments to the middleware function. That’s why it works seamlessly there—Express takes care of invoking the middleware for you behind the scenes.

Alternative Clean Approach

If you prefer a more concise setup, you can make createUser directly return the middleware function:

exports.createUser = passport.authenticate('local-signup', {
  successRedirect : '/all',
  failureRedirect : '/signup',
  failureFlash : true
});

Then keep your route definition the same:

app.post('/signup', user.createUser);

Either way, the core fix is ensuring the middleware returned by passport.authenticate gets called with the necessary request/response objects to do its job.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 03:55:55