上QQ阅读APP看书,第一时间看更新
Refactoring the app.js file with the new middleware
At this time, we have to do a major restructuring of the app.js
file to include the new middleware that we will use.
We will show you step by step how to include each middleware and at the end, we will see the complete file:
- Open
app.js
and add the following lines beforevar app = express()
:// ODM With Mongoose var mongoose = require('mongoose'); // Modules to store session var session = require('express-session'); var MongoStore = require('connect-mongo')(session); // Import Passport and Warning flash modules var passport = require('passport'); var flash = require('connect-flash');
This is a simple import process.
- Add the following lines after
app.set('view engine', 'ejs')
:// Database configuration var config = require('./server/config/config.js'); // connect to our database mongoose.connect(config.url); // Check if MongoDB is running mongoose.connection.on('error', function() { console.error('MongoDB Connection Error. Make sure MongoDB is running.'); }); // Passport configuration require('./server/config/passport')(passport);
- Note that we are using a
config.js
file in the first line; later we will create this file. - Add the following lines after
app.use(express.static(path.join(__dirname, 'public')))
:// required for passport // secret for session app.use(session({ secret: 'sometextgohere', saveUninitialized: true, resave: true, //store session on MongoDB using express-session + connect mongo store: new MongoStore({ url: config.url, collection : 'sessions' }) })); // Init passport authentication app.use(passport.initialize()); // persistent login sessions app.use(passport.session()); // flash messages app.use(flash());