How to separate the routes and models from app.js using NodeJS and Express

后端 未结 3 643
生来不讨喜
生来不讨喜 2021-01-30 04:13

I\'m creating an app using Node and Express. However, I can see it\'ll soon become difficult to manage all the routes that are placed inside app.js. I have placed

3条回答
  •  情话喂你
    2021-01-30 04:53

    Since I don't like repetition, here's what I do:

    // app.js
    //...
    var routes = requireDir('./routes'); // https://www.npmjs.org/package/require-dir
    for (var i in routes) app.use('/', routes[i]);
    //...
    

    And each file in routes is like:

    // routes/someroute.js
    var express  = require('express');
    var router   = express.Router();
    
    router.get('/someroute', function(req, res) {
        res.render('someview', {});
    });
    
    module.exports = router;
    

    This way you can avoid long repetitive lists like this one:

    app.use('/'           , require('./routes/index'));
    app.use('/repetition' , require('./routes/repetition'));
    app.use('/is'         , require('./routes/is'));
    app.use('/so'         , require('./routes/so'));
    app.use('/damn'       , require('./routes/damn'));
    app.use('/boring'     , require('./routes/boring'));
    

    Edit: these long examples assume each route file contains something like the following:

    var router = express.Router();
    router.get('/', function(req, res, next) {
        // ...
        next();
    });
    module.exports = router;
    

    All of them could be mounted to "root", but what for them is "root", is actually a specific path given to app.use, because you can mount routes into specific paths (this also supports things like specifying the path with a regex, Express is quite neat in regards to what you can do with routing).

提交回复
热议问题