我在node.js应用程序中使用明确的验证。登录路线正常工作,但我无法注销。该会话保留在我的MongoDB数据库中,并在单击注销链接时有一个新的到期时间。
我尝试了req.session.destroy((和req.session.cookie.expires = new date((。getTime((,cookie在单击登录按钮时会过期,但没有任何效法。
>index.js
中的Express-Session代码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');
});
我希望会话被摧毁,并且该页面将被重定向到登录页面。谁能告诉我我做错了什么?
尝试此
module.exports = (req, res) => {
if(req.session) {
req.session.cookie.maxAge = 0
delete req.session
}
res.redirect('/auth/login')
}