2017-05-16 95 views
0

我想將我的護照變量傳遞給我的路由器類,但似乎無法找到如何執行此操作。傳遞變量以表示路由器

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中做些什麼來獲得護照變量?

回答

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; 
} 
+0

謝謝。之前沒有工作,因爲我忘了返回路由器。 –