Hello guys I have this server.js
setup, and im trying to pass msg "logged out successfully" on /login
page when user will log out. The problem here is that im using so much middleware and I'm kinda lost in what's going on. I tried to pass it by res.locals, req.session, req.session.flash, but some method or middleware probably is deleting sessions.
Something is going on in .delete()
method probably, because everything seems to work just fine if im passing variables outside of this method. Seems like maybe .delete()/method_override middleware has some features that I dont know about OR i cannot use next() properly. Help guys i spent so much time on this already.
Alternatively, if you could tell me, how to check if i was redirected to /login
then I could easily figure out some work arounds but right now im stucked. Also is there any better way of passing that message? Should I use queries for this example? I'm kinda perfectionist and don't like this ugly urls :D
require('dotenv').config()
const express = require('express')
const app = express()
const bcrypt = require('bcrypt')
const users = []
const flash = require('express-flash')
const session = require('express-session')
const methodOverride = require('method-override')
const passport = require('passport')
const initializePassport = require('./passport-config')
initializePassport(passport,
email => users.find(user => user.email === email),
name => users.find(user => user.name === name))
app.set('view engine','ejs')
app.use(express.json())
app.use(express.urlencoded({extended:false}))
app.use(flash())
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false
}))
app.use(passport.initialize())
app.use(passport.session())
app.use(methodOverride('_method'))
app.get('/login', checkNotAuthenticated, (req, res) => {
console.log(req.session.test) //> undefined
res.render('login', { msg: req.flash('info')}) //> undefined
})
app.delete('/logout', (req, res) => {
req.logOut((err) => err ? next(err) : '')
req.flash('info', 'logged out successfully') // ?
req.session.test = true; // ?
res.redirect('/login')
})
function checkNotAuthenticated(req, res, next){
if(!req.isAuthenticated()){
return next()
}
res.redirect('/')
}
Solved with 2 different workarounds: (besides the easy but not the prettiest one - passing query in an url)
global.location
need to check (global.location === 'logout') in latter method, then delete global.location
flash()
// app.get('/logout', (req, res) => { // 2
// req.flash('info', 'Logged out succesfully')
// res.redirect('/login')
// })
app.delete('/logout', (req, res) => {
req.logOut((err) => err ? next(err) : void(0))
global.location = 'logout' // 1 ->
res.redirect('/login')
// res.redirect('/logout)
})
Seems like flash() .locals, .session and others simply doesn't work in .delete function with method-override.