Fixing TypeError: Object #<IncomingMessage> has no method 'flash' in ExpressJS version 4.2

Currently, I am utilizing ExpressJS 4.2 and PassportJS for authenticating local users. Everything seems to be working smoothly except for when attempting to display a failureFlash message. Below is my configuration setup, thank you in advance!

==== Necessary Dependencies in app.js

var express      = require('express');
var path         = require('path');
var favicon      = require('static-favicon');
var logger       = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser   = require('body-parser');
var passport     = require('passport')
var mongoose     = require('mongoose');
var flash        = require('connect-flash');

==== Configuration Settings in app.js

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser('secret'));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));

==== /admin Route (routes/admin.js)

router.post('/admin', passport.authenticate('loginAdmin',{ successRedirect: '/panel',
                                                failureRedirect: '/admin',
                                                failureFlash: true }));

==== Passport File (config/passport.js)

passport.use('loginAdmin', new LocalStrategy(
  function(username, password, done) {
    modeloUsuario.findOne({ nombre: username, password: password }, function(err, user)  {
      if (err) { return done(err); }
      if (!user) {
        return done(null, false, { message: 'Incorrect username.' });
      }
      return done(null, user, {message: "invalid login"}); //<- error problem
    });
  }
));

==== Lastly, the package.json file

{
  "name": "test",
  "version": "0.0.2",
  "private": true,
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "express": "~4.2.0",
    "connect-flash": "latest",
    "static-favicon": "~1.0.0",
    "morgan": "~1.0.0",
    "cookie-parser": "~1.0.1",
    "body-parser": "~1.0.0",
    "debug": "~0.7.4",
    "ejs": "~0.8.5",
    "passport": "latest",
    "passport-local": "latest",
    "mongoose": "latest"
  }
}

The encountered error:

Github/express-auth/node_modules/passport/lib/middleware/authenticate.js:111
          req.flash(type, msg);
              ^
TypeError: Object #<IncomingMessage> has no method 'flash'

Answer №1

Make sure to set up the flash library in your middleware within app.js.

To resolve this issue, add app.use(flash) before setting up passport middleware.

For additional information, refer to connect-flash #usage.

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

Error: The value for 'prepareStyles' property is undefined and cannot be read

Can anyone provide some guidance on this code snippet? I am struggling to understand the error message I am receiving. import React, {PropTypes} from 'react'; import TransactionListRow from './TransactionListRow'; import {Table, TableB ...

Exploring Unicode Symbols for Icon Selection

I'm currently working on integrating an icon picker into my application that will enable the user to select a mathematical operator for data comparison. While I have successfully implemented the fontawesome-iconpicker on the page, I am encountering d ...

A step-by-step guide on uploading a CSV file in Angular 13 and troubleshooting the error with the application name "my

I am currently learning angular. I've generated a csv file for uploading using the code above, but when I try to display it, the screen remains blank with no content shown. The page is empty and nothing is displaying Could it be that it's not ...

Is there a way to communicate with the Microsoft bot from within the bot itself, ensuring that the message follows the dialog flow and receives the appropriate response?

It would make more sense if the title of this were "how can I ensure the bot responds smoothly in case context is lost or there's a server restart during a user interaction with the bot. It's confusing as it is and I need to break down the planni ...

A single element containing two duplicates of identical services

I am encountering an issue with my query builder service in a component where I need to use it twice. Despite trying to inject the service twice, it seems that they just reference each other instead of functioning independently, as shown below: @Component( ...

What could be causing the malfunction in this JavaScript and WebRTC code?

<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Vid Chat App</title> </head> <body> <video controls autoplay> </video> <script src="https: ...

React modal not triggered on click event

As a newcomer to react, I am exploring a modal component import React, { useState, useEffect } from 'react'; import { Modal, Button } from "react-bootstrap"; function TaskModal(props) { return ( <Modal show={pro ...

npm installation encounters an error

I'm facing a problem with npm installation as it keeps failing. Despite this, I can see that the node-modules folder has been generated in my local path. How can I resolve this issue shown in the image above? Check out the installation error here. ...

Localhost is unable to process AngularJS routes containing a dot in the URL

When using the route provider and setting this specific route: .when('/:name/:id', { It successfully navigates to my desired path and executes the code when I enter: https://localhost.myapp.com:9000/Paul/123 However, it fails to work with this ...

Varnish is preventing HTML redirects from being executed properly

I've encountered an issue with my setup involving Varnish 3.0 on Ubuntu 11 and ExpressJS v2.5.8 (running on Node.js 0.6). When I try to do a redirect using Express, it works fine without Varnish in between. However, when Varnish is added into the mix, ...

Tips for interpreting JSON information and showcasing it with the assistance of Ajax in JQuery?

There's a request made to the system via AJAX that returns JSON as a response, which is then displayed in an HTML table. The HTML code for displaying the data looks like this: <table id="documentDisplay"> <thead> <tr ...

Navigating through tabs in a Meteor application: How to maintain the active tab when using the back button

I am working on a multi-page meteor application where each page includes a navigation template. To switch between pages, I am using iron-router. The user's current page is indicated by setting the appropriate navigation link's class to 'ac ...

steps for setting up socket.io client

Would it be possible to reference the socket.io client library using a relative path like: src="/socket.io/socket.io.js" instead of the absolute path: src="https://miweb:6969/socket.io/socket.io.js" To establish a connection with the library, typically ...

Connect the plotly library to interact with the data in a Vue.js application through

I'm currently working on a project that involves using vue.js and the plot.ly JavaScript graph library. I am trying to figure out how to bind "pts" to the data's "TestSentences" in Vue. Below is my code snippet, thanks to everyone who has provide ...

The pdfkit library seems to have an issue where it is failing to properly embed images within the

Currently, I am working on using PDFkit along with node.js for converting an HTML webpage into a PDF format. The HTML page contains multiple image tags within the body tag. Unfortunately, when I convert the HTML to PDF, the resulting page appears complete ...

Increase the value of count (an AJAX variable) by 4 upon clicking the button, then send it over to the PHP script

I'm facing an issue where my AJAX variable is only updating once by +4 each time a button is pressed. I need assistance on how to make it continuously work. index.php - AJAX <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.m ...

Looking for guidance on integrating cookies with express session? Keep in mind that connect.sid is expected to be phased out

Within my app.js file, I have the following code snippet: app.use(session({secret: 'mySecret', resave: false, saveUninitialized: false})); While this setup functions correctly, it triggers a warning message: The cookie “connect.sid” will ...

The malfunction of Bootstrap modal in iterative scenarios

I am currently developing a comprehensive method for handling AJAX requests in my JavaScript code, but I am facing some issues with the Bootstrap modal not functioning as intended. Here is the HTML structure: <div class="modal fade" id="consult_modal_ ...

"Vue.js integrates seamlessly with Tracking.js for advanced tracking

Has anyone successfully integrated the tracking.js library into a vueJS application? I followed these steps to install the package: npm install --save tracking After that, I defined the library in my main.js file like this: import tracking from 't ...

Configuring the baseUrl for Axios in a Vue.js application triggers the sending of a request

I have encountered an issue in my app where Axios automatically makes a request to the baseUrl without me explicitly making one. This occurs even when the app is loaded in the browser. In my main.js file, I have set the baseUrl using: axios.defaults.baseU ...