Express+MongoDB+Passport-JWT认证报错:未启用passport.initialize()中间件
Hey, let's fix that error you're hitting. The root cause is straightforward—your Express app isn't setting up Passport's core initialization middleware, which is required before you can use any of Passport's authentication strategies like JWT.
第一步:添加Passport初始化中间件到主应用入口
You're missing the passport.initialize() middleware in your main Express app setup (probably in a file like server.js or app.js). Passport needs this to attach its methods (like req.login, which your error log mentions is failing) to the request object.
Here's how to add it:
- First, make sure you're requiring Passport in your main app file:
const passport = require('passport'); - Then, before mounting your routes, add the initialization middleware. It should come after any request-body parsing middleware (like
express.json()) but before your router:const express = require('express'); const mongoose = require('mongoose'); const passport = require('passport'); const router = require('./router'); const app = express(); // Parse incoming JSON bodies (required for signup requests) app.use(express.json()); // Initialize Passport - this is the line you were missing! app.use(passport.initialize()); // Mount your routes router(app); // Connect to MongoDB and start the server mongoose.connect('your-mongodb-connection-string') .then(() => { app.listen(3090, () => { console.log('Server running on port 3090'); }); }) .catch(err => console.error('MongoDB connection error:', err));
第二步:修复路由里的拼写错误
While we're at it, I noticed a typo in your router.js file that could cause issues later:
// You have an extra 's' in "sesssion" const requireAuth = passport.authenticate('jwt', { sesssion: false }); // Fix it to: const requireAuth = passport.authenticate('jwt', { session: false });
为什么这能解决问题?
The error message points to req.login failing—this method is added to the request object by passport.initialize(). Without that middleware, Passport hasn't set up its core functionality, so when your JWT strategy tries to authenticate a user and call req.login, it throws an error.
Once you add passport.initialize() to your app's middleware chain, Passport will properly initialize itself, and your JWT authentication should work as expected.
内容的提问来源于stack exchange,提问作者bigmugcup

