How to export all routes in Express?

前端 未结 3 1456
南方客
南方客 2021-02-02 03:52

I have an NodeJS Express app that is getting really big in just one file (app.js).

I want to export all my routes into a single, external file, say ./lib/routes.j

3条回答
  •  误落风尘
    2021-02-02 04:10

    What I do is group my routes by controller. For each group of related routes (users, shopping cart, whatever), I make a controller file that lives in app/controllers/foo.js where foo is the controller name. In my main javascript server file (where all your code currently lives), I require each controller by name and then call its setup function, passing in my express app object, and allow the controller to add whatever routes it needs.

    ['api', 'authorization', 'users', 'tests'].map(function(controllerName) {
        var controller = require('./controllers/' + controllerName);
        controller.setup(app);
     });
    

    Inside each controller, I do something like:

    exports.setup = function(app) {
        app.get('/dashboard', function(req, res) {
            res.render('dashboard', {
                username: req.session.username
            });
        });
    };
    

提交回复
热议问题