【问题标题】:Not able to logout using express-session in node.js无法在 node.js 中使用 express-session 注销
【发布时间】:2020-07-03 21:18:28
【问题描述】:

我在我的 node.js 应用程序中使用 express-session 进行身份验证。登录路线工作正常,但我无法注销。当单击注销链接时,会话将保留在我的 mongodb 数据库中,并具有新的到期时间。

我已尝试 req.session.destroy() 和 req.session.cookie.expires = new Date().getTime() 让 cookie 在单击注销按钮时过期,但没有任何效果。

index.js 中的快速会话代码

app.use(expressSession({
    secret: 'secret',
    cookie: { maxAge: 60 * 60 * 24 * 1000 }, //if maxAge is set to anything between 1000 and 9000 the logout button works
    resave: false,
    saveUninitialized: false,
    store: new mongoStore({
        mongooseConnection: mongoose.connection
    })
}));

loginUser.js

const bcrypt = require('bcrypt')
const User = require('../database/models/User')

module.exports = (req, res) => {
    const {
        email,
        password
    } = req.body;
    // try to find the user
    User.findOne({
        email
    }, (error, user) => {
        if (user) {
            // compare passwords.
            bcrypt.compare(password, user.password, (error, same) => {
                if (same) {
                    req.session.userId = user._id
                    res.redirect('/')
                } else {
                    res.redirect('/auth/login')
                }
            })
        } else {
            return res.redirect('/auth/login')
        }
    })
}

storeUser.js

const User = require('../database/models/User')

module.exports = (req, res) => {
    User.create(req.body, (error, user) => {
        if (error) {
            const registrationErrors = Object.keys(error.errors).map(key => error.errors[key].message)

            req.flash('registrationErrors', registrationErrors)
            return res.redirect('/auth/register')
        }
        res.redirect('/')
    })
}

auth.js

const User = require('../database/models/User')

module.exports = (req, res, next) => {
    User.findById(req.session.userId, (error, user) => {
        if (error || !user) {
            return res.redirect('/')
        }

        next()
    })
}

logout.js

module.exports = (req, res) => {
    req.session.destroy(() => {
        res.redirect('/auth/login');
});

我希望会话被破坏并且页面被重定向到登录页面。谁能告诉我我做错了什么?

【问题讨论】:

  • 您将哪个 mongo 库用作会话存储?连接蒙戈?
  • 你可以试试req.session = nullreq.logout();
  • @Saroj 是的,我正在使用 connect mongo。
  • @TruongDang 尝试但没有成功。
  • 我认为添加 ttl 会有所帮助。 npmjs.com/package/connect-mongo

标签: node.js mongodb express-session


【解决方案1】:

试试这个

module.exports = (req, res) => {
  if(req.session) {
    req.session.cookie.maxAge = 0
    delete req.session
  }
  res.redirect('/auth/login')
}

【讨论】:

    猜你喜欢
    • 2021-07-06
    • 2015-12-20
    • 2021-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-10
    相关资源
    最近更新 更多