Dzyuv001
Dzyuv001

Reputation: 318

Express Session use leads to a requires a middleware function

I am attempting to implement sessions and passport.js on a small test website to see how to use user authentication.

var express = require("express");
var expressSession = require("express-sessions");
var mongoose = require("mongoose");
var passport = require("passport");
var bodyParser = require("body-parser");
var LocalStrategy = require("passport-local");
var passportLocalMongoose = require("passport-local-mongoose");
var User = require("./models/user");
var app = express();

mongoose.connect("mongodb://localhost/authDemoApp");
app.use(bodyParser.urlencoded({
extended: true}));
app.set("view engine", "ejs");

app.use(expressSession({
secret: "This is one hell of a secret",
resave: false,
saveUninitialized: false
}));

app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

app.listen(3000, function () {
console.log("Its running!!!");
});

The error that I get i:

throw new TypeError('app.use() requires a middleware function')
^
TypeError: app.use() requires a middleware function

I added call back function to app.use(expressSession...) making it:

app.use(function(err){
if (err){
console.log(err);
}else {
expressSession(...
}
});

The err value came back with:

IncomingMessage {
 _readableState:
ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: BufferList { head: null, tail: null, length: 0 },
length: 0,
pipes: null,
pipesCount: 0,

etc...

My question is middleware function and how do I add it to the app.use(expressSession etc... ?

Upvotes: 0

Views: 718

Answers (1)

Sridhar
Sridhar

Reputation: 11786

The module is express-session, but your require statement is loading express-sessions.

Correcting this, the program runs.

var express = require("express");
var expressSession = require("express-session");
var mongoose = require("mongoose");
var passport = require("passport");
var bodyParser = require("body-parser");
var app = express();

mongoose.connect("mongodb://localhost/authDemoApp");
app.use(bodyParser.urlencoded({
  extended: true
}));
app.set("view engine", "ejs");

app.use(expressSession({
  secret: "This is one hell of a secret",
  resave: false,
  saveUninitialized: false
}));

app.use(passport.initialize());
app.use(passport.session());

app.listen(3000, function () {
  console.log("Its running!!!");
});

There is even a Github issue for it. #446 app.use() requires middleware functions

Upvotes: 2

Related Questions