mdv
mdv

Reputation: 945

ExpressJS 4.2 and flash error (TypeError: Object #<IncomingMessage> has no method 'flash')

im using ExpressJS 4.2 and PassportJS to authenticate local users. Everything is fine except when I try to rise failureFlash message. This is my conf, thanks in advance!

==== requires 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');

==== config 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
    });
  }
));

==== Finally, my package.json

{
  "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 error:

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

Upvotes: 2

Views: 3215

Answers (1)

Waldo Jeffers
Waldo Jeffers

Reputation: 2279

You haven't initiliazed flash in your middleware in app.js.

Adding app.use(flash) before passport middleware should fix the problem.

See connect-flash #usage for more info.

Upvotes: 3

Related Questions