How to export all routes in Express?

前端 未结 3 1446
南方客
南方客 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:07

    Why not do something like this:

    // logout.js
    module.exports = function(req, res){
      res.render('logout', {
        username: req.session.username
      });
    });
    
    // dashboard.js
    module.exports = function(req, res){
      res.render('dashboard', {
        username: req.session.username
      });
    });
    
    // login.js
    module.exports = function(req, res){
      res.render('login', {
        badLogin: false,
        loginError: false
      });
    });
    
    // app.js
    app.get('/logout', require('logout'));
    app.get('/dashboard', require('dashboard'));
    app.get('/login', require('login'));
    

    Also, you could imagine easily using http://nodejs.org/docs/v0.4.8/api/fs.html#fs.readdir to loop through a routes directory and load these up programmatically.

    You could even do something along the lines of...

    module.exports.handler[] = {
        method : 'get',
        route  : '/login',
        action : res.render('login', {
           badLogin: false,
           loginError: false
        });
    }
    

    Though I think I'd spend a little time thinking about how to simplify that.

提交回复
热议问题