我尝试添加connect-mongo以便在nodeJS重新启动时保存会话。
根据我添加的文档:
MongoStore = require('connect-mongo')(session),
在我的require('express-session')
我添加了
store: new MongoStore({
url: mongooseDB,
touchAfter: 24 * 3600
})
并注释掉app.use(passport.session());
我收到错误:ReferenceError:未定义会话,指向MongoStore = require('connect-mongo')(session),
我已添加了我的app.js文件以供参考。我该如何解决这个问题?
'use strict';
const express = require('express'),
app = express(),
bodyParser = require('body-parser'),
mongoose = require('mongoose'),
MongoStore = require('connect-mongo')(session),
passport = require('passport'),
flash = require('connect-flash'),
LocalStrategy = require('passport-local'),
methodOverride = require('method-override'),
logger = require('morgan'),
cookieParser = require('cookie-parser'),
User = require('./models/user'),
faker = require('faker'),
path = require('path');
const indexRoute = require('./routes/index'),
usersRoute = require('./routes/users'),
giftsRoute = require('./routes/gifts.js'),
searchRoute = require('./routes/search');
const mongooseDB = 'mongodb://localhost/giftcashing';
mongoose.connect(mongooseDB);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/bower_components', express.static(__dirname + '/bower_components'));
app.use(methodOverride("_method"));
app.use(flash());
app.use(require('express-session')({
secret: 'anything',
resave: false,
saveUninitialized: false,
store: new MongoStore({
url: mongooseDB,
touchAfter: 24 * 3600
})
}));
// PASSPORT CONFIGURATION
app.use(passport.initialize());
// app.use(passport.session());
// use static authenticate method of model in LocalStrategy
passport.use(new LocalStrategy(User.authenticate()));
// use static serialize and deserialize of model for passport session support
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use(function (req, res, next) {
res.locals.currentUser = req.user;
res.locals.error = req.flash('error');
res.locals.success = req.flash('success');
next();
});
// catch 404 and forward to error handler
// app.use(function(req, res, next) {
// var err = new Error('Not Found');
// err.status = 404;
// next(err);
// });
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
// render the error page
res.status(err.status || 500);
res.render('error');
});
app.use('/', indexRoute);
app.use('/users', usersRoute);
app.use('/gifts', giftsRoute);
app.use('/search', searchRoute);
module.exports = app;

答案 0 :(得分:4)
调用时未初始化变量session
MongoStore = require('connect-mongo')(session)
。
在初始化session = require('express-session')
之前添加MongoStore
。