Express框架中session值获取返回undefined错误求助
Hey there, let's troubleshoot why you can't retrieve the req.session.test value you set earlier. Based on your code snippets and common gotchas with express-session, here are the key areas to check:
1. Make Sure Cookies Are Being Sent With Your Request
When you send the GET request to /passport/me, your browser needs to automatically include the session cookie that was set during the /passport/login POST request. If you're using frontend AJAX calls (like with axios or fetch), you need to explicitly enable credential handling:
- For axios:
axios.get('/passport/me', { withCredentials: true }) - For fetch:
fetch('/passport/me', { credentials: 'include' })
If your frontend is running on a different port/domain than your backend (e.g., frontend on localhost:8080, backend on localhost:3000), you'll also need to configure CORS on the backend to allow credentials:
First install the cors package:
npm install cors --save
Then add this to your app.js before the express-session middleware:
const cors = require('cors'); app.use(cors({ origin: 'http://localhost:8080', // Replace with your frontend's actual URL credentials: true }));
2. Verify Middleware Order (And Check for Cookie-Parser)
Your current order of mounting express-session after static assets and before routes is correct, but double-check that no other custom middleware is modifying the req object before the session middleware runs.
Also, if you're using cookie-parser anywhere in your app, it must be mounted before express-session:
const cookieParser = require('cookie-parser'); // Mount cookie-parser first app.use(cookieParser()); // Then mount express-session app.use(expressSession({ secret: '123456', resave: false, saveUninitialized: false, cookie: { secure: false, // Set to true only if using HTTPS in production httpOnly: true, maxAge: 86400000 // 1 day expiration } }));
Note: The resave and saveUninitialized options you used are deprecated in newer Express versions—switching to false is better practice, and adding explicit cookie settings helps avoid scope issues.
3. Test Session Functionality in a Single Request
To rule out session storage issues, create a quick test route that sets and retrieves the session value in one go:
router.get('/test-session', (req, res) => { req.session.test = 'test data'; console.log('Set session:', req.session.test); console.log('Get session immediately:', req.session.test); res.send('Session test complete'); });
If this works, the problem is definitely with cookie handling across separate requests, not the session system itself.
4. (Optional) Switch to a Persistent Session Store
By default, express-session uses in-memory storage, which is fine for development but can lose sessions if the server restarts. If you want to rule this out, you can use a persistent store like connect-redis, but this is likely not the issue here since you're testing in the same session.
内容的提问来源于stack exchange,提问作者shamon shamsudeen

