问题
So, I just started with expressjs 4.0.0
and came across the express.Router()
object, which is really nice.
Problem is, now that all my routes are in another file, how do I expose an object to the routes file ?
serverjs file:
...
var passport = require('passport');
var router = require('./app/routes.js')(passport); //WILL NOT WORK
app.use('/', router);
app.listen(8080);
routes.js file:
...
var express = require('express');
var router = express.Router(); //new feature in expressjs 4.0
//routes go here
module.export = router;
So, how should I access passport object in router file ? Should I create a new object or is there a way to pass the server.js object to router.js file ?
回答1:
You could wrap your router.js in a function that accepts the passport object as parameter and handles the instantiation of the router also. Then, module.export that function instead of only the router.
EDIT: including example
server.js:
var passport = require('passport');
var router = require('./app/routes')(app, passport);
app.use('/', router);
app.listen(8080);
routes.js:
var express = require('express');
module.exports = function(app, passport){
var router = express.Router();
// routes go here
// do stuff with passport
return router;
}
回答2:
this way works
var express = require('express')
, home = require(_pathtoyourroutes.js)
app.get('/', home.index);
//router.js
exports.index = function(req, res){
var d = new Date();
res.render('index', { title: 'Hello world', description:'Hello world this is a awesome site.', stylesheet: 'body.css', jsfile: 'home.js' });
};
来源:https://stackoverflow.com/questions/23159803/expose-vs-creating-object-in-router-file-of-nodejs