Express: How to pass app-instance to routes from a different file?

后端 未结 8 1056
误落风尘
误落风尘 2020-11-29 16:34

I want to split up my routes into different files, where one file contains all routes and the other one the corresponding actions. I currently have a solution to achieve thi

8条回答
  •  死守一世寂寞
    2020-11-29 16:57

    Node.js supports circular dependencies.
    Making use of circular dependencies instead of require('./routes')(app) cleans up a lot of code and makes each module less interdependent on its loading file:


    app.js

    var app = module.exports = express(); //now app.js can be required to bring app into any file
    
    //some app/middleware setup, etc, including 
    app.use(app.router);
    
    require('./routes'); //module.exports must be defined before this line
    


    routes/index.js

    var app = require('../app');
    
    app.get('/', function(req, res, next) {
      res.render('index');
    });
    
    //require in some other route files...each of which requires app independently
    require('./user');
    require('./blog');
    


    -----04/2014 update-----
    Express 4.0 fixed the usecase for defining routes by adding an express.router() method!
    documentation - http://expressjs.com/4x/api.html#router

    Example from their new generator:
    Writing the route:
    https://github.com/expressjs/generator/blob/master/templates/js/routes/index.js
    Adding/namespacing it to the app: https://github.com/expressjs/generator/blob/master/templates/js/app.js#L24

    There are still usecases for accessing app from other resources, so circular dependencies are still a valid solution.

提交回复
热议问题