我想将护照变量传递给路由器类,但似乎无法知道如何执行此操作。
Server.js:
const session = require('express-session');
const path = require('path');
const passport = require('passport');
const routes = require('./routes')(passport); //pass variable here
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const mongoose = require('mongoose');
const configDB = require('./config/database.js');
const flash = require('connect-flash');
const app = express();
mongoose.connect(configDB.url);
app.use(express.static(path.join(__dirname, '/dist')));
app.use(cookieParser());
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(session({
name: 'sessionid',
secret: 'changethis',
resave: false,
saveUninitialized: true,
cookie: {secure: true}
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(routes);
app.listen(8080, function () {
console.log('App started on port 8080');
});
/routes/index.ejs :(我想在这里使用护照变量。)
const routes = require('express').Router();
const path = require('path');
const api = require('./api');
routes.use('/api', api);
routes.get('/*', function (req, res) {
res.sendFile(path.join(path.dirname(require.main.filename) + '/dist/index.html'));
});
module.exports = routes;
我需要在index.ejs中做些什么来获取护照变量?
答案 0 :(得分:2)
您需要更改 /routes/index.ejs 以导出工厂功能。
const path = require('path');
const api = require('./api');
module.exports = function factory(yourVar) {
const routes = require('express').Router();
routes.use('/api', api);
routes.get('/*', function (req, res) {
res.sendFile(...);
});
return routes;
}