How can I quickly send a flash logout notification through Express or verify if a redirection has occurred

Hey everyone, I'm currently dealing with an issue in my server.js setup where I'm trying to display the message "logged out successfully" on the /login page when a user logs out. The problem stems from using multiple middleware and feeling overwhelmed by it all. I've attempted to pass the message using res.locals, req.session, and req.session.flash, but it seems like some method or middleware is causing the sessions to be deleted.

I suspect something might be happening within the .delete() method, as everything works fine when passing variables outside of that section. It's possible that the .delete() method or the method_override middleware has certain features I'm not aware of, or maybe I'm not using next() correctly. Any help would be greatly appreciated as I've already invested significant time into this.

On another note, if anyone knows how to check if I've been redirected to the /login page, that could potentially lead me to some workarounds for the current issue. Additionally, are there better ways to pass messages? Should queries be used in this scenario? As a perfectionist, I'm not a fan of messy 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)                   
    res.render('login', { msg: req.flash('info')})
})

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('/')
}

Answer №1

Resolved using 2 alternative solutions: (aside from the straightforward but less elegant method of passing query in a URL)

1. utilizing the global.location

it's important to verify (global.location === 'logout') in the second approach, then remove global.location

2. initially redirecting to GET method, then sending message to flash()

// app.get('/logout', (req, res) => {                    //  2
//     req.flash('info', 'Logged out successfully')
//     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)
})

It appears that flash() .locals, .session and other methods simply do not function in the .delete operation when using method-override.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best method for choosing a document from a Firebase based on its creation time?

Currently delving into Firebase as part of my project, struggling with setting queries in the Database. I've provided a breakdown of my Firebase database structure below: Looking to retrieve the most recently created document from the 'subscrip ...

The console in React displays values, but fails to render them on the DOM

I am attempting to dynamically load options for a select element based on another select's value. I pull the data from an array that will eventually contain more information. The issue I am facing is that even though I successfully filter the data, t ...

What could be causing the response data from an AJAX request to be in error instead of success?

My JSON data is securely stored on , and I can access it through a unique URL. Here is the specific URL: The JSON data found at the above URL is: { "glossary": { "title": "Suyog", "GlossDiv": { ...

ways to incorporate searching within JSON data using AJAX and jQuery in JavaScript

My search box needs to have JSON data appended into it. Below is the HTML code: <input type="search" id="merchantName" name="merchant" placeholder="enter merchant name"></input> I have JSON data containing merchant names that I want to appen ...

Bring back enhanced assortment using Mongoose

I am currently working with a stack that includes nodejs, express, mongoose, and angularjs. My task involves updating a collection called Lists which contains various properties, including an array of items. The issue I am facing is that when I push a new ...

The AJAX call failed because the web service was not properly configured, resulting in a missing parameter value being

I'm encountering an issue with my ajax call that displays a specific message. [WebMethod(EnableSession = true)] public static string UpdateTotalPrice(List<TicketPriceAjax> jsonTickets) { // conducting server-side processing return "a u ...

Encountering difficulties decoding URL-encoded data in Express

Here is a straightforward server I created: var app = require('express')(); var bodyParser = require('body-parser'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.post('/update', (req, ...

Modal does not display the plothover tooltip

I am utilizing the flot Chart library to display a graph within a modal window. Everything is functioning properly except for the Tooltip popover not appearing when I hover over the plot. Below is my JavaScript code: $(document).on('click',&apos ...

Shutting down browser with WebdriverIO and launching a new one

I am facing a challenge in my application testing process. I need to simulate a scenario where I close the browser and session, then open a new browser and session to check if the previously entered data can be successfully recalled by passing certain laun ...

What is the best way to use AJAX to load a PHP file as a part

I'm exploring different methods for making an AJAX call with an included file. Let's create a simple working example. Initially, I have my main index.php file which contains the following content. In this file, I aim to access all the data retur ...

Guide to selecting a date using JavaScript in Selenium with Ruby

I'm having some trouble selecting a date from a date picker field using JavaScript in Selenium WebDriver. I've attempted the code below, which does navigate to the date window successfully, but I can't figure out how to execute the JavaScrip ...

Conceal the header and footer during the loading of particular pages

For my Angular 1.x application, I needed a way to hide the header and footer on specific pages. To achieve this, I added a 'navigateOut' data property to my state definitions. Using ng-if in my template, I was able to show/hide elements such as t ...

Ways to automatically expand all table groupings

Currently, I am experimenting with the Material UI table that includes a group by feature. While exploring the code, I noticed that the groups can be expanded or collapsed using a click event. However, my goal is to have all groups expanded by default as s ...

Having completed "npm link" and "npm i <repo>", the module cannot be resolved despite the presence of "main" and "types" in the package.json file

Here is the contents of my package.json file: { "name": "ts-logger", "main": "dist/index.js", "types": "dist/index.d.ts", "scripts": { "install": "tsc" ...

What is the best way to instruct Vite to exclude specific files within a directory from the build process?

After initializing a fresh Vue application with the command npm create vue, I implemented a functionality where the app fetches a configuration at runtime and extracts a component name from it. These dynamic components reside in a directory called "pluggab ...

jQuery is currently displaying the value stored in the variable in a phrased format

Having trouble with the initial phase of a major project. I am attempting to showcase the JSON output received from the URL below. It displays the data perfectly when I directly enter the URL into a web browser. However, when I assign the URL to a variable ...

Has the Angular 2 community established a standardized ecosystem?

As a developer specializing in Angular 1, I am now eager to dive into the world of Angular 2. However, navigating through the changes and rewrites can feel like traversing a confusing maze. All of the comprehensive guides I have come across date back to l ...

Special character Unicode regex for names

After spending the entire day reading about regex, I am still struggling to fully grasp it. My goal is to validate a name, but the regex functions I have found online only include [a-zA-Z], omitting characters that I need to allow. Essentially, I require ...

Guide on how to perform a POST request within a service worker?

I am faced with the challenge of sending a POST request to the back-end every time a client clicks on a Push notification from the front-end, in order to confirm that the client has received the notification. Here is the system I currently have in place f ...

detect and handle errors when deploying the Node.js function

I'm currently attempting to use code I found on Github to insert data into a Firestore database, but unfortunately, I keep encountering an error. Here's the specific error message: 21:1 error Expected catch() or return promise/catch-or-re ...