Express会话无法将属性用户设置为undefined

时间:2019-06-21 07:03:58

标签: node.js mongodb express express-session

我正在尝试通过邮递员登录我的用户,并且每次尝试收到错误消息

  

无法设置未定义的属性“用户”

我通过控制台注销了该用户,并能够确认是否从数据库查询中返回了该用户。

adminController

exports.postAdminLogin = async (req, res, next) => {
    const userToFind = req.body.username,
        password = req.body.password;
    // Get data from the db that should be displayed  to user client
    try {
        const user = await User.findOne({username: userToFind});
        // If no user is found send 404 status and message
        if (!user) {
            return res.status(422).send('Invalid email or password');
        }
        // If a user is found compare password with the password passed from the request
        return bcrypt.compare(password, user.password)
        // If password matches
            .then(doMatch => {
                if (doMatch) {
                    req.session.isLoggedIn = true;
                    req.session.username = user.username;
                    res.session.user = user;
                    return req.session.save(err => {
                        if (err) {
                            console.log(`Error when trying to login with err ${err}`);
                        }
                        res.status(200);
                        next();
                    })
                }
            })
            // If bcrypt encounters an error
            .catch(err => {
                res.status(500).send(`This is the error ${err}`);
            });
        // If an error occurs when finding a user from the db
    } catch (err) {
        err ? res.status(500).send(err) : console.log('No user found')
    }
    next()
};

server.js

const path = require("path"),
    express = require("express"),
    app = express();
require('dotenv/config');

// imported dependencies
const bodyParser = require("body-parser"),
    mongoose = require("mongoose"),
    session = require('express-session'),
    MongoDBStore = require('connect-mongodb-session')(session),
    cors = require('cors'),
    log = console.log,
    User = require('./models/User');

    // Mongo Db Storage
const dbStorage = new MongoDBStore({
    uri: process.env.DATABASE_SESSION_URI,
    collection: 'sessions'
});

app.use((req, res, next) => {
    res.locals.isAuthenticated = req.session.isLoggedIn;
    next();
});

app.use((req, res, next) => {
    if (!req.session.user) {
        return next();
    }
    User.findById(req.session.user)
        .then(user => {
            if (!user) {
                return next();
            }
            req.user = user;
            next()
        })
        .catch(err => {
            next(new Error(err))
        });
});

// where to find routes
const adminRoutes = require("./routes/admin");
const menuRoutes = require("./routes/menu");

app.use((error, req, res, next) => {
    res.status(500);
    next();
});

// session config
app.use(require("express-session")({
    secret: process.env.DATABASE_SECRET,
    resave: false,
    saveUninitialized: false
}));

// points to static folder
app.use(express.static(path.join(__dirname, "public")));

// middleware
app.use(cors());
app.use(bodyParser.json());

app.use(session({
    secret: process.env.SESSION_SECRET,
    resave: true,
    saveUninitialized: true,
    store: dbStorage
}));

app.use('/admin', adminRoutes);
// app.use('/menu', menuRoutes);

// production db
mongoose.connect(process.env.DATABASE_URL, {useNewUrlParser: true})
    .then(() => {
        log(`Connected to the database`);
        app.listen(process.env.SERVER_PORT, err => {
        err ? log(`Error occurred trying to connect to port: ${process.env.SERVER_PORT} with err code: ${err}`) : log(`Server connected on port: ${process.env.SERVER_PORT}`);
        });
    })
    .catch(err => {
        console.log(err)
    });

我希望用户能够登录并将会话存储到数据库

2 个答案:

答案 0 :(得分:0)

您正在初始化会话两次。 在这里:

app.use(require("express-session")({
    secret: process.env.DATABASE_SECRET,
    resave: false,
    saveUninitialized: false
}));

在这里:

app.use(session({
    secret: process.env.SESSION_SECRET,
    resave: true,
    saveUninitialized: true,
    store: dbStorage
}));

删除其中之一。

然后,您需要将会话初始化移至任何试图访问会话的代码之上。

这是您第一次尝试访问会话。

app.use((req, res, next) => {
    res.locals.isAuthenticated = req.session.isLoggedIn;
    next();
});

所以您需要在其之上进行会话初始化。

app.use(session({
    secret: process.env.SESSION_SECRET,
    resave: true,
    saveUninitialized: true,
    store: dbStorage
}));

// now you can access session
app.use((req, res, next) => {
    res.locals.isAuthenticated = req.session.isLoggedIn;
    next();
});

答案 1 :(得分:0)

尝试将会话配置放在路由之上:

app.use(require("express-session")({
    secret: process.env.DATABASE_SECRET,
    resave: false,
    saveUninitialized: false
}));

const adminRoutes = require("./routes/admin");
const menuRoutes = require("./routes/menu");