Express Session的使用导致需要中间件功能

时间:2018-07-23 13:29:22

标签: node.js express express-session

我正在尝试在一个小型测试网站上实现会话和passport.js,以查看如何使用用户身份验证。

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!!!");
});

我得到我的错误:

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

我在app.use(expressSession...)中添加了回调函数,使其成为

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

返回err的值:

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

等...

我的问题是中间件功能,如何将其添加到app.use(expressSession etc...中?

1 个答案:

答案 0 :(得分:1)

模块为express-session,但是您的require语句正在加载express-sessions

更正此问题,程序将运行。

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!!!");
});

甚至还有一个Github问题。 #446 app.use() requires middleware functions