req.session 在使用 express-session 时未定义

req.session is undefined when using express-session

以下是我的会话设置代码:

import app from './server.js';
import dotenv from 'dotenv';
import mongoose from 'mongoose';
import session from 'express-session';
import {default as connectMongo} from 'connect-mongo';

dotenv.config();

const port = process.env.PORT || 8000;
const MongoURI = process.env.BLOG_DB_URI;
const MAX_AGE = process.env.MAX_AGE;

mongoose
  .connect(MongoURI, { 
    useNewUrlParser: true,
    useUnifiedTopology: true
  })
  .then((client) => {
    const mongoDBstore = connectMongo.create({
      mongoUrl: MongoURI,
      client: client,
      collection: "mySessions" 
    });
    console.log('session: ' + session);

    app.use(
      session({
        secret: process.env.SESSION_SECRET, 
        resave: false, 
        saveUninitialized: false, 
        store: mongoDBstore,
        cookie: {
          path: '/',
          httpOnly: false,
          maxAge: MAX_AGE,
          sameSite: false
        }
      })
    );
    
    app.listen(port, () => console.log(`listening on port: ${port}`));
    })
  .catch((err) => console.log(err));

下面是我的用户登录代码:

static async loginUser(req, res, next) {
        try{
            const user = await User.findOne({userName: req.body.userName});
            !user && res.status(400).json('Please enter correct username');

            const valid = await bcrypt.compare(req.body.password, user.password);
            !valid && res.status(400).json('Invalid Password');

            const sessUser = {
                id: user._id,
                userName: user.userName,
                email: user.email
            };
            console.log('req.session: ' + req.session);
            req.session.user = sessUser; 
            
            res.status(200).json(sessUser);
        } catch(err) {
            res.status(500).json(`login error: ${err}`);
        }
    }

现在,当我转到我的登录路径时:'/api/user/login' 并尝试登录现有用户时,出现错误:

login error: TypeError: Cannot set property 'user' of undefined

在打印 req.session 的值时,它显示为未定义。 有人可以给我一些关于我可能做错了什么的想法吗? 提前致谢。

问题出在我声明中间件的顺序上。 app.use(session(...)) 必须在 app.use('/api/users/login', function(...)) 之前。否则 res.session 将保持未定义状态。